gpt4 book ai didi

javascript - 从子组件 React js 更改父级的状态

转载 作者:行者123 更新时间:2023-11-30 15:26:07 25 4
gpt4 key购买 nike

class Parent extends React.Component{
constructor(props){
super(props);
this.state={
data : props.data
};
}

render(){
for(let i=0;i<this.state.data.length;i++){
let row = this.state.data[i];
//row.value = 0 here
outs.push(<Children row={row}/>);
}
}
}

class Children extends React.Component{
constructor(props){
super(props);
}

render(){
let row = this.props.row;
this.changeRowValue(row);
if(row.value == 1){
//do something
}
....
}

changeRowValue(row){
row.value = 1;
//how do i set the state of data object here ?
}
}

数据对象示例

数据 =

[0] => {value : 0,someother : somevalue},

[1] => {value : 0,someother : somevalue},

[2] => {value : 0,someother : somevalue}

如果我在 Children 类中更改 data[1].value = 1 的值,我该如何设置整个 data 的状态对象?

最佳答案

您需要更新父对象中的数据,让 React 自己处理子对象的更新。一个看起来如何的例子是:

class ParentComponent extends React.Component {
onChangeValue = (index, newData) => {
let data = this.state.data;
data[index] = newData;

this.setState({ data });
}

render() {
let outs = [];

for (let i = 0; i < 10; i++) {
let row = this.state.data[i];

outs.push(
<ChildComponent index={ i } row={ row } onChangeValue={ this.onChangeValue }/>
);
}

return <div>{ outs }</div>;
}
}

class ChildComponent extends React.Component {
...

onChangeValue() {
const { index, onChangeValue } = this.props;
this.props.onChangeValue(index, { someNewValue });
}
}

当您想更新子项中的某些内容时,您可以调用其 onChangeValue 方法,该方法又会调用父项的 onChangeValue

关于javascript - 从子组件 React js 更改父级的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42940053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com