【问题标题】:React - Passing State to child componentReact - 将状态传递给子组件
【发布时间】: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


    【解决方案1】:

    使用value 而不是defaultValue 来控制来自父组件的输入。

    class EngInput extends React.Component {
      render() {
        return (
          <input
            type="number"
            value={this.props.value}
            onChange={this.props.onChange}
          />
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 2022-07-15
      • 2019-08-09
      • 1970-01-01
      • 2019-03-08
      • 2020-07-04
      • 2023-03-21
      • 2019-09-18
      • 2023-02-01
      相关资源
      最近更新 更多