Reactjs 从父组件更新子组件
嗨,我是新的反应,我有一些情况。我想将数据从父级更新到子级,但子级数据更改不会更新到父级 这是我的父组件=>Reactjs 从父组件更新子组件,reactjs,react-component,Reactjs,React Component,嗨,我是新的反应,我有一些情况。我想将数据从父级更新到子级,但子级数据更改不会更新到父级 这是我的父组件=> export default class ShiftMaster extends React.Component{ constructor(props){ super(props); this.state = { monshift : new TempShift(), } } handelChange = event =>{
export default class ShiftMaster extends React.Component{
constructor(props){
super(props);
this.state = {
monshift : new TempShift(),
}
}
handelChange = event =>{
this.setState({
[event.target.id]:event.target.value
},()=>{
});
}
<ShiftDaily
shiftday={this.state.monshift}
/>
这是名为ShiftDaily的子组件
export default class ShiftDaily extends React.Component{
constructor(props){
super(props);
this.state = {
offin_f:props.shiftday.offin_f,
offout_f:props.shiftday.offout_f,
offin_1h:props.shiftday.offin_1h,
offout_1h:props.shiftday.offout_1h,
offin_2h:props.shiftday.offin_2h}
}
handleChange = event =>{
this.setState({
[event.target.id]:event.target.value
},()=>{
});
}
<Form.Control id="offout_f"
className="form-control-sm"
value={this.state.offout_f}
onChange={this.handleChange}/>
导出默认类ShiftDaily扩展React.Component{
建造师(道具){
超级(道具);
this.state={
offin\u f:props.shiftday.offin\u f,
offout\f:props.shiftday.offout\f,
offin_1h:props.shiftday.offin_1h,
offout_1h:props.shiftday.offout_1h,
offin_2h:props.shiftday.offin_2h}
}
handleChange=事件=>{
这是我的国家({
[event.target.id]:event.target.value
},()=>{
});
}
我无法将父级的句柄更改传递给子级,因为子组件中的值更改不会反映在父级数据中
但是当我在父
monshift
中更改时,我想更新到子值并显示数据。我可以知道如何实现这一点吗?谢谢您应该使用道具。*
直接声明,而不将其分配给此.state
内部ShiftDaily
原因是构造函数
在渲染期间只运行一次,因此您所做的任何更改都不会通过道具反映。*
传递给ShiftDaily
(因为此.state
不会再次更新,因为它在构造函数中设置过一次)
因此,您需要1.完全摆脱
构造函数
和this.state={…}
赋值。2.移除
ShiftDaily.handleChange
,因为道具将从ShiftMaster
更新,并在道具更改时向下进入ShiftDaily
。3.直接使用
this.props.
值
<Form.Control
id="offout_f"
className="form-control-sm"
value={this.props.shiftday.offout_f} />
您应该使用
道具。*
直接声明,而不将其分配给此.state
内部每日移位
原因是构造函数
在渲染期间只运行一次,因此您所做的任何更改都不会通过道具反映。*
传递给ShiftDaily
(因为此.state
不会再次更新,因为它在构造函数中设置过一次)
因此,您需要1.完全摆脱
构造函数
和this.state={…}
赋值。2.移除
ShiftDaily.handleChange
,因为道具将从ShiftMaster
更新,并在道具更改时向下进入ShiftDaily
。3.直接使用
this.props.
值
<Form.Control
id="offout_f"
className="form-control-sm"
value={this.props.shiftday.offout_f} />
谢谢,我正按照你的建议尝试。根据你的建议,我可以知道如何将数据从家长传递到孩子。当前传递是正确的吗?因为this.props.offout\u f始终未定义。并且我不需要更改孩子组件?@Jze我更新了上面的答案。我错了,因为我使用了this.props.offout\u f
this.props.shiftday.offout\f
此外,您可以从以下链接获得对其工作的更清晰和理解:,谢谢,我正按照您的建议进行尝试。根据您的建议,我可以知道如何将数据从父级传递到子级吗。当前传递是正确的吗?因为this.props.offout\f始终未定义。我不需要c是否在子组件上挂起?@Jze我更新了上面的答案。我错了,因为我使用了this.props.offout\f
而不是this.props.shiftday.offout\f
。此外,您还可以从以下链接获得对其工作的更清晰和理解:,