Reactjs React-将状态传递给子组件
我的父类,它保存整个应用程序状态Reactjs React-将状态传递给子组件,reactjs,Reactjs,我的父类,它保存整个应用程序状态 class App extends Component { constructor(props) { super(props); this.state = { inputValue: 1, }; this.handleChange = this.handleChange.bind(this); }; handleChange(event) { const target = event.targe
class App extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: 1,
};
this.handleChange = this.handleChange.bind(this);
};
handleChange(event) {
const target = event.target;
const newValue = target.value;
if( Math.sign(newValue) === 1 ) {
this.setState({
inputValue: newValue
});
}
}
render() {
return (
<EngInput type="number" value={this.state.inputValue} onChange={this.handleChange}/>
);
}
}
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
输入值:1,
};
this.handleChange=this.handleChange.bind(this);
};
手变(活动){
const target=event.target;
const newValue=target.value;
if(数学符号(newValue)==1){
这是我的国家({
inputValue:newValue
});
}
}
render(){
返回(
);
}
}
我将状态作为道具传递到的子组件
class EngInput extends React.Component {
render() {
return (
<input
type="number"
defaultValue={this.props.value}
onChange={this.props.onChange}
/>
);
}
}
类EngInput扩展了React.Component{
render(){
返回(
);
}
}
我试图实现的逻辑是-子输入组件应该只接受正数。如果是负数,则状态不应更改,UI应更新为inputValue而不是newValue
但是,上面代码中发生的是,即使状态没有变为非负值,UI仍然接受负值
如何实现这样的逻辑:如果值为负值,UI仍应显示来自状态的旧正值。
使用value
而不是defaultValue
来控制来自父组件的输入
类EngInput扩展了React.Component{
render(){
返回(
);
}
}