reactjs - 如何在 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,
});
解决方案
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} />
);
}
}
推荐阅读
- amazon-web-services - AWS:将其重新分配给另一个实例后无法连接到弹性 IP
- android - android活动中的浏览按钮
- excel - HLLAPI 函数 99 未按预期工作
- amazon-s3 - 未设置 AWS PHP SDK ContentType
- mysql - MySQL - CONCAT - 有没有办法连接字符串并将其用作变量?
- android - 条形线mpandroid图表
- python - 使用 Pandas 0.22 的 AttributeError:pandas._libs.lib 没有属性“isscalar”
- javascript - 如何限制用户登录尝试Angular.js(打字稿)
- c - sscanf() 跳过分隔符和宽度
- html - 如何在目录周围换行