简体   繁体   中英

Pass props to the main component from child (React Native)

I have two components. The first component is the main component and it has title 'Select'/'Unselect'

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>
      );
  }

}

Also I have child component, and when the user clicks on "onPush" function - title Select All/Unselect should changes. So user clicks on "InfoUserList" component, but the state of this title is changed in main "Contacts" component.

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>
    );
  }
}

To inform a parent of a child change, you need to pass an event handler from the parent to the child, then have the child call the event handler method when the event occurs.

  1. Define the event handler in the parent.

    onInfoUserListCheckChange() { // do something here }

Note: You may need to bind the event handler this in the parent constructor to access this.

this.onInfoUserListCheckChange = onInfoUserListCheckChange.bind(this);
  1. Raise the event from the child.

    onPush() { //... if (this.props.onCheckChange) { this.props.onCheckChange( //the checked value); }
    }

  2. Pass the handler to the child from the parent

    < InfoUserList onCheck={this.onCheckChange} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM