Props 属性(外部数据)
Props外部数据
传入props给B组件
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { name: "Zhoujia22" };
}
onClick = () => {};
render() {
return (
<B name={this.state.name} onClick={this.onClick}>
hi
</B>
);
}
}
//外部数据被包装成一个对象
//{name:"Zhoujia22",onClick:...,children:"hi"}
此处的onClick是一个回调
初始化
class B extends React.Component {
constructor(props) {
super(props);
}
render() {}
}
要么不初始化,即不写constructor
要么初始化,必须写全套
这么做了以后,this.props就是外部数据对象的地址了
读取
class B extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div onClick={this.props.onClick}>
{this.props.name}
<div>{this.props.children}</div>
</div>
);
}
}
//通过this.props.xxx读取
不允许写props,但是有以下两种方法
改props的值(一个地址)
this.props.xxx={/*另一个对象*/}
不要写这样的代码,没有意义
理由:既然是外部数据,就应该由外部更新
改props的属性
this.props.xxx='hi'
不要写这样的代码,没有意义
理由:既然是外部数据,就不应该从内部改值
原则
应该由数据的主人对数据进行更改
componentWillReceiveProps
class App extends React.Component {
constructor(props) {
super(props);
this.state = {x: 1};
}
onClick = () => {
this.setState({x: this.state.x + 1});
};
render() {
return <div className={'App'}>
App
<button onClick={this.onClick}>+1</button>
<B name={this.state.x}></B>
</div>;
}
}
class B extends React.Component {
componentWillReceiveProps(nextProps, nextContext) {
console.log('旧的props');
console.log(this.props);
console.log('props变化了');
console.log('新的props');
console.log(nextProps);
}
render() {
return <div>{this.props.name}</div>;
}
}
componentWillReceiveProps钩子
当组件接受新的props时,会触发此钩子
现在这个钩子已经弃用