我在布局中有一个子组件,我也想传递一个 Prop 值。但我不知道怎么办。在下面的类中,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 }
})
);
}
关于javascript - 在 react 中将值传递给子组件(this.props.children),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50073052/