首页 > 解决方案 > 如何在 react-native 中将子状态传递给父级?

问题描述

我的子组件在我想在父组件中使用的函数中设置了状态“imageLink”。但即使我用 setState 设置它,我也总是得到空值。

task.then(() => {
    taskSnapshot.ref.getDownloadURL().then(downloadURL => {
      const image = {uri: downloadURL};
      this.setState({imageLink: image});
    });
  });

在父组件中

db.collection('childs')
    .add({
      name: this.state.name,
      firstname: this.state.firstname,
      birthDate: this.state.chosenDate,
      gender: this.state.gender,
      birthLocation: this.state.birthLocation,
      rang: this.state.rang,
      imageLink: this.state.imageLink,
    });

标签: reactjsreact-native

解决方案


React 组件不会像那样共享 state/setState 方法。

您想要的是提升子组件的 state

与其在子组件中包含包含“imageLink”的状态,不如将其添加到父组件的状态(看起来您已经这样做了),然后通过 props 传递一个方法来将该值设置给子组件:

class Child extends React.Component {
    // Here's your method
    someMethod = () => {
        // Now we can use the "setImageLink" prop to set the parent component's "imageLink" state value.
        const { setImageLink } = this.props;

        task.then(() => {
            taskSnapshot.ref.getDownloadURL().then(downloadURL => {
                const image = { uri: downloadURL };

                setImageLink(image);
            });
        });
    }

    render () {
        return null;
    }
}

class Parent extends React.Component {
    state = {
        imageLink: "",
        // ... rest of your state
    }

    setImageLink = (imageLink) => {
        this.setState({ imageLink });
    }

    render () {
        const { imageLink } = this.state;       

        return (
            <Child setImageLink={this.setImageLink} />
        );
    }
}

推荐阅读