1.父子组件
ReactJS中数据的流动是单向的
父组件传递数据给子组件: 可以通过设置子组件的props传递数据给子组件。
子组件改变父组件的数据: 可以在父组件中传一个callback(回调函数)给子组件,子组件调用callback可改变父组件的数据。
实例:点击子组件,改变父组件的背景色
export default class SampleOne extends Component {
constructor(props) {
super(props);
this.state = {
color: 'white',
};
}
// 改变curItem的回调函数
_changeColor(color) {
this.setState({ color: color });
}
render() {
return (
<View style={
{ backgroundColor: this.state.color, flex: 1 }}>
<Child text='Child one' color='red'
changeColor={ (color) => this._changeColor.bind(this, color) }/>
<Child text='Child two' color='white'
changeColor={ (color) => this._changeColor.bind(this, color) }/>
</View>
);
}
}
class Child extends Component {
render() {
return (
<Text style = {
{ fontSize: 50, margin: 20 }}
onPress={this.props.changeColor(this.props.color) }>
{this.props.text}
</Text>
);
}
}
2.兄弟组件
当两个组件不是父子关系,但有相同的父组件时,将这两个组件称为兄弟组件。
兄弟组件不能直接相互传送数据,此时可以将数据挂载在父组件中。
由两个组件共享:如果组件需要数据渲染,则由父组件通过props传递给该组件;
如果组件需要改变数据