在上一节中,我们讲到了React组件,说了如何使用ES6类创建一个React组件并在其他的地方使用它。这一节我们将讲到React组件的两大灵魂——props和state。
props
不知道大家还记不记得xml标签中的属性,就像这样:
<class id="1"> <student id="1">John Kindem</student> <student id="2">Alick Ice</student></class>
这样一个xml文件表达的意思是1班有两个学生,学号为1的学生名字为John Kindem,学号为2的学生名字为Alick Ice,其中id就是属性,你可以把它看做一个常量,它是只读的。
html继承自xml,而JSX从莫种意义上又是html和js的扩展,属性的概念自然得到了传承。
在React中,我们使用props这一概念向React组件传递只读的值,就像这样:
// 假设我们已经自定义了一个叫Hello的组件ReactDom.render( <Hello firstName={'John'} lastName={'Kindem'}/>, document.getElementById('root'));
在调用React组件的时候,我们可以像上面一样向组件传递一些常量,以便组件在内部调用。而调用的方法,就像下面这样:
class Hello extends React.Component { constructor(props) { super(props); } render() { return ( <div> <h1>Hello, {this.props.firstName + ' ' + this.props.lastName}</h1> </div> ); }}ReactDom.render( <Hello firstName={'John'} lastName={'Kindem'}/>, document.getElementById('root'));
在组件内部获取传递过来的props,只需要使用this.props对象即可,但是在使用之前,记得复写组件的构造函数,并且接受props的值以调用父类构造。
当然,props也能够设置默认值,向下面这样:
class Hello extends React.Component { constructor(props) { super(props); } static defaultProps = { firstName: 'John', lastName: 'Kindem' }; render() { return ( <div> <h1>Hello, {this.props.firstName + ' ' + this.props.lastName}</h1> </div> ); }}ReactDom.render( <Hello/>, document.getElementById('root'));
只需在ES6类中声明一个static的props默认值即可,运行效果和上面一样。
props没有多复杂,稍微练习即可习得。
state、组件生命周期
你可能回想,如果我想在React组件中添加动态效果怎么办?目前学过的知识好像无法解决这一问题。
这一问题需要使用React组件的state来解决,state即状态的意思,在React中,所有会变化的控制变量都应该放入state,每当state中的内容变化时,页面的相应组件将会被重新渲染,另外,state完全是组件内部的东西,外部无法向内部传递state,也无法直接改变state的值。
先来举一个例子:
新闻热点
疑难解答
图片精选