我有兩個組件。第一部分是主要成分,它有標題「選擇」 /「取消選擇」將道具傳遞給兒童的主要組件(React Native)
export default class Contacts extends React.Component {
constructor(props) {
super(props);
this.state = { check: 0 };
}
oneItem() {
this.setState({ check: this.state.check === 0 ? 1 : 0 });
}
render() {
const { check } = this.state;
const infoUserLists = UserList;
const dataUserList = infoUserLists.map((infoUserList, index) => <InfoUserList
key={`infu_${index + 1}`}
infoUserList={infoUserList}
selectAll={this.state.check}
/>);
return (
<View>
<View>
<TouchableOpacity onPress={() => this.oneItem()}>
<NormalText label={check === 0 ? 'Select All' : 'Unselect'} />
</TouchableOpacity>
{dataUserList}
</View>
);
}
}
我也有子組件,並且當"onPush"
功能的用戶點擊 - 標題選擇全部/取消選擇應該改變。因此用戶點擊"InfoUserList"
組件,但該標題的狀態在主要的"Contacts"
組件中發生了變化。
export default class InfoUserList extends React.Component {
constructor(props) {
super(props);
this.state = { check: 0, label: 'Select All' };
}
onPush() {
this.setState({ check: this.state.check === 0 ? 1 : 0 });
}
render(){
const { infoUserList, selectAll } = this.props;
const { check } = this.state;
return (
<View key={infoUserList.name}>
<TouchableOpacity onPress={() => this.onPush()}>
<Image source={ check === 1 || selectAll === 1 ? iconsLnk.choose : iconsLnk.plus } />
</TouchableOpacity>
</View>
);
}
}
看一看這一點。 https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17您需要在父類中創建回調函數並將其傳遞給子類。然後在子組件中使用this.props.callbackFunction –