react 函数式组件中使用props 您所在的位置:网站首页 react组件api中与设置状态 react 函数式组件中使用props

react 函数式组件中使用props

2023-07-19 00:31| 来源: 网络整理| 查看: 265

我们之前学习的一直是组件实例上的props,是可以通过this访问组件实例的,比如props,可以通过this.props访问,但是在函数式组件中,不存在组件实例。

function Person() { return ( 姓名:{name} 性别:{sex} 年龄:{age + 1} ); }

这是一个比较简单的函数式组件,和上文一样,想展示姓名,性别,年龄信息。

class Person extends React.Component { static propTypes = { name: PropTypes.string.isRequired, sex: PropTypes.string, age: PropTypes.number, speak: PropTypes.func, }; // 设置默认属性 static defaultProps = { sex: "女", age: 18, }; state = {}; render() { const { name, sex, age } = this.props; // prop是只读的 // this.props.name = "jack"; return ( 姓名:{name} 性别:{sex} 年龄:{age + 1} ); } }

类组件种有一行关键代码

const { name, sex, age } = this.props;

所有的props数据都是从this.props,也就是组件实例对象中取出来的,而在函数式组件中this是undefined。 正确的获取数据方式是从参数中获取

function Person(props) { return ( 姓名:{name} 性别:{sex} ); } ReactDOM.render(, document.getElementById("test"));

在这里插入图片描述 完整代码,包括限制

function Person(props) { const { name, sex } = props; return ( 姓名:{name} 性别:{sex} ); } Person.propTypes = { name: PropTypes.string.isRequired, sex: PropTypes.string, age: PropTypes.number, speak: PropTypes.func, }; Person.defaultProps = { sex: "女", age: 18, }; ReactDOM.render( , document.getElementById("test") );


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有