-
顺传(父传子)
props
class SonCompoent extends Component{
render() {
return (
<View style={styles.sonViewStyle}>
<Text>{this.props.name}的儿子</Text>
</View>
);
};
}
class FatherComponet extends Component {
render() {
return (
<View>
<SonCompoent name={this.props.name}/>
</View>
);
}
}
export default class ReactDemo extends Component {
render() {
return (
<FatherComponet name="xxx" />
);
}
}
通过ref拿到控件给控件传值,ref="son"
拿到子类
class SonCompoent extends Component{
constructor(props){
super(props);
this.state = {
money:0
}
}
receiveMoney(money){
this.setState({
money:money
});
}
render() {
return (
<View>
<Text>{this.props.name}的儿子</Text>
<Text>总共收到{this.state.money}生活费</Text>
</View>
);
};
}
class FatherComponet extends Component {
render() {
return (
<View>
<Text onPress={()=>{
this.refs.son.receiveMoney(1000);
}}>发生活费</Text>
<SonCompoent ref="son" name={this.props.name} />
</View>
);
}
}
export default class ReactDemo extends Component {
render() {
return (
<FatherComponet name="xxx" />
);
}
}
-
逆传(子传父)
在父组件中定义一个处理接收到值的方法,把这个方法传递给子组件,并且绑定this,子组件就能通过this.props拿到这个方法调用
class SonCompoent extends Component{
makeMoney (money) { //把这个方法传递给子组件
this.props.receiveMoney(money);
}
render() {
return (
<View>
<Text>{this.props.name}的儿子</Text>
<Text onPress={this.makeMoney.bind(this,100)}>赚100块钱</Text> //子组件就能通过this.props拿到这个方法调用
</View>
);
};
}
class FatherComponet extends Component {
constructor(props){
super(props);
this.state = {
money:0
};
}
receiveMoney(money) { //在父组件中定义一个处理接收到值的方法
var m = this.state.money;
m += money;
this.setState({
money:m
});
}
render() {
return (
<View>
<SonCompoent name={this.props.name+'A'} receiveMoney={this.receiveMoney.bind(this)}/> //并且绑定this
<SonCompoent name={this.props.name+'B'} receiveMoney={this.receiveMoney.bind(this)}/>
<Text>爸爸收到{this.state.money}</Text>
</View>
);
}
}
export default class ReactDemo extends Component {
render() {
return (
<FatherComponet name="xxx" />
);
}
}
通知
//发通知
DeviceEventEmitter.emit('makeMoney',100);
//接受通知
this.lister = DeviceEventEmitter.addListener('makeMoney',(money)=>{
this.setState({
money:money
});
})
// 移除通知
componentWillUnmount() {
this.lister.remove();
}
网友评论