我有一个React应用程序,我试图修改我从父组件传递的道具。我想要做的是,一旦我点击了我的子组件中的计数器,就可以修改父道具,并且可以在我的两个组件中重复使用。
如何修改子组件中的父道具,然后在我的应用中的所有子组件中重复使用这些修改的道具?
App.js
class App extends React.Component {
constructor(props) {
super(props);
this.setInitState = this.setInitState.bind(this)
this.state = {value: 0}
}
setInitState() {
this.setState({
value: 0 // I want to modify and reuse this in my child components
})
}
changeValue(e) {
console.log('parent change', e)
let value = e;
this.setState({value: value});
}
render() {
return (
<Wrapper>
<Grid>
<Row>
<CostBox />
<Input changeValue={this.changeValue} {...this.state} />
<TotalBox changeValue={this.changeValue} {...this.state} />
</Row>
</Grid>
</Wrapper>
)
}
}
const Wrapper = styled.section`
padding: 4em;
background: #2B3636;
`;
render(<App />, document.getElementById("root"));
Input.js
class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.value,
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
subtractUnit() {
this.setState({
value: this.state.value - 1 // once the button has been clicked, I want to have this modified value be modified in the parent and then reusable throughout this and my other component
});
}
addUnit() {
this.setState({
value: this.state.value + 1 // once the button has been clicked, I want to have this modified value be modified in the parent and then reusable throughout this and my other component
});
}
render() {
return(
<Col md={6}>
<CenterBox>
<h5>
<form>
<InputLabel># OF UNITS<br />
<UnitInput type='number' id="total-units" value={this.state.value} onChange={this.handleChange.bind(this)}></UnitInput>
</InputLabel>
</form>
<IconContainer onClick={this.subtractUnit.bind(this)}><MdRemoveCircleOutline style={iconLeft} /></IconContainer>
<IconContainer onClick={this.addUnit.bind(this)}><MdAddCircleOutline style={iconRight} /></IconContainer>
</h5>
</CenterBox>
</Col>
)
}
}
TotalBox.js
class TotalBox extends React.Component {
constructor(props) {
super(props);
console.log(this.props);
this.state = {
value: this.props.value, // once one of the counter buttons is clicked I want to use it in this component to output on the final total label
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
return (
<Col md={3}>
<RightBox>
<TotalCostHeader>TOTAL COST</TotalCostHeader>
<TotalCostLabel>${this.state.value * 175.50}</TotalCostLabel>
</RightBox>
</Col>
)
}
}
答案 0 :(得分:0)
永远不要改变道具,如果你的项目中有一个活跃的话,你可能会从失败中警告过。您正在搜索的流程可能是
使用方法 myMethod 更改 state.myAttr - &gt;的父级 myAttr 和 myMethod 作为道具传递给了儿童 - &gt;孩子调用 props.myMethod 并从父母那里接收更新的道具