【发布时间】:2019-01-20 17:26:51
【问题描述】:
保存整个 App 状态的父类
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}/>
);
}
}
我将状态作为道具传递给我的子组件。
class EngInput extends React.Component {
render() {
return (
<input
type="number"
defaultValue={this.props.value}
onChange={this.props.onChange}
/>
);
}
}
我试图实现的逻辑是 - 子输入组件应该只接受正数。如果它是负数,则状态不应更改,并且 UI 应更新为 inputValue 而不是 newValue。
但是,上面代码中发生的情况是,即使状态没有变为非负值,UI 仍然接受负值。
如何实现这样的逻辑,如果值为负,UI 仍应显示状态中旧的正值。
【问题讨论】:
标签: reactjs