![](/img/trans.png)
[英]Passing function to child component this.props.children method undefined
[英]Passing a value onto a child component (this.props.children) in react
我在Layout中有一個子組件,我也想傳遞props值。 但是我不知道如何。 在下面的類中,layoutFileDataRequest()在單擊事件中從子組件接收字符串變量。 需要將該值發送到this.props.children組件之一,以便可以更新。
我該怎么做呢? 在React.cloneElement(child, {
下面的代碼中React.cloneElement(child, {
不會更改,它始終保持不變,這意味着我無法更新child prop。
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 }
})
);
}
實際代碼沒有任何問題,我猜正在發生的唯一事情是,在<FileListing />
組件中沒有任何內容,並且調用了prop(method) projectFileDataRequest
並將其傳遞給<Layout />
的孩子。
TL; DR ...這是您的代碼,在收到<FileListing />
的click事件之后,就可以工作和更新<Layout />
的子級。
https://codesandbox.io/s/5050w0p9kx
希望對您有幫助
您的代碼實際上可以正常工作。 這是cloneElement的參數:
React.cloneElement(
element,
[props],
[...children]
)
您正在將數據作為道具傳遞給子組件。
檢查一下:stackblitz.com/edit/react-xhwmd3?file=Layout.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.