【发布时间】:2023-03-06 23:18:01
【问题描述】:
我有一个 React 应用程序,我正在尝试修改我从父组件传递的道具。我想要做的是,一旦我在我的子组件中单击了一个计数器,就可以修改父道具并能够在我的两个组件中重用。
如何在我的子组件中修改父 props,然后在我的应用中的所有子组件中重复使用这些修改后的 props?
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>
)
}
}
【问题讨论】:
标签: javascript html reactjs components state