javascript - 在反应中将值传递给子组件(this.props.children)
问题描述
我在 Layout 中有一个子组件,我也想传递一个 props 值。但我不知道怎么做。在下面的类中,layoutFileDataRequest() 在单击事件时从子组件接收字符串变量。需要将该值发送到 this.props.children 组件之一,以便它可以更新。
我该怎么做呢?在下面的代码中 React.cloneElement(child, {
,它始终保持不变,这意味着我无法更新 child 道具。
export default class Layout extends React.Component {
constructor(props) {
super(props)
this.layoutFileDataRequest = this.layoutFileDataRequest.bind(this);
this.state = {
newData: '',
returnData: 'test',
}
}
/**
* Received request from server add it to
* react component so that it can be rendered
*/
layoutFileDataRequest(data) {
this.setState({ returnData:data })
}
renderChildren() {
return React.Children.map(this.props.children, child => {
console.log(this.state.returnData);
return React.cloneElement(child, {
data: this.state.returnData
})
});
}
/**
* Render request
*
*
*/
render() {
const { location } = this.props;
const title = this.state.newData;
return (
<div id="app-container" class={title}>
<Nav location={location} />
<main id="main">
<h1>{title}</h1>
<section>
{this.renderChildren()}
</section>
</main>
<Project layoutFileDataRequest={this.layoutFileDataRequest} />
<Footer />
</div>
);
}
}
export default class Project extends React.Component {
constructor(props) {
super(props)
this.projectFileDataRequest = this.projectFileDataRequest.bind(this);
this.state = {
newData: [],
}
}
/**
* Received request from server add it to
* react component so that it can be rendered
*/
projectFileDataRequest(data) {
this.props.layoutFileDataRequest(data);
}
/**
* Received request from server add it to
* react component so that it can be rendered
*/
componentDidMount() {
ApiCalls.readSassDirData()
.then(function (serverData) {
this.setState({ newData: serverData[0].data })
}.bind(this));
}
/**
* Render request
*/
render() {
const listOfObjects = this.state.newData;
return (
<aside id="project">
<h2>Files</h2>
<FileListing listOfObjects={listOfObjects} projectFileDataRequest={this.projectFileDataRequest} />,
</aside>
);
}
}
解决方案
我认为错误出在 renderChildren 函数中。
代码
renderChildren() {
return React.Children.map(this.props.children, child => {
console.log(this.state.returnData);
return React.cloneElement(child, {
data: this.state.returnData
})
});
}
新代码
renderChildren(){
return this.props.children.map(child =>
React.cloneElement(child, {
data: {...this.state.returnData }
})
);
}
推荐阅读
- r - rsqlite 表和润滑
- for-loop - 如何使用 awk 和 grep 计算两个文件的平均值
- html - Angular Ts 更新 for 循环中的元素
- c# - 如何对双向链表进行 MergeSort?
- c# - 如何获取已从asp.net内容页面中的无序列表的listitem中选择的文本
- amazon-dynamodb - 无法处理 DyanmoDB 命令行中的保留关键字“Key”
- angular - API 代码在 Angular 中有效,但在 Ionic 中无效
- python - Python:使用 pandas 导入 csv 文件时出现 ID 错误
- python - Flask 服务器无响应端口 - 如何杀死所有线程
- javascript - jQuery AJAX 在点击时运行两次