【问题标题】:React - Reset component inputReact - 重置组件输入
【发布时间】:2017-02-09 09:18:19
【问题描述】:

我在使用组件时遇到了困难,我希望你们能帮助我。 所以我创建了一个自定义组件,它返回用户在输入中输入的格式化值(如果用户输入'1999-9-9',它返回'1999-09-09 00:00'),值为分配给父级的状态(handleCustomInputValueChange)。 现在..问题是,如果我单击“数字”类型并用随机字符填充输入,保存并转到“日期时间”,输入保持不变,它不会重置或不会从道具中获取数据。它具有来自“数字”的旧值。 在许多情况下,使用 componentWillReceiveProps() 方法可以解决这个问题,但不是在这里,因为我只想将数据发送给父级。我不需要将该数据发送回我的“CustomInput”。

父组件:

    handleCustomInputValueChange(changeEvent) {
        this.setState({value: changeEvent});
    }
    ...
    switch(type) {
        case 'NUMERIC':
            return <CustomInput data={value} type="numeric" callbackParent={handleCustomInputValueChange} />
            break;
        case 'DATETIME':
            return <CustomInput data={value} type="datetime" callbackParent={handleCustomInputValueChange} />
            break;
    }

子组件

export default class CustomInput extends Component {
    constructor(props) {
        super();

        this.state = {
            value: props.data || ''
        }
    }

    handleChange(event) {
        /* formatting data */
        callbackParent(formattedData);
    }

    render() {
        return <input type="text" onChange={this.handleChange} value={this.state.value} />;
    }
}

那么..有没有办法在切换到另一种类型后重置输入?

谢谢!

【问题讨论】:

  • 您可以使用onBlur 事件来重置输入。 onBlur 事件将在 Input 失去焦点时触发。

标签: javascript reactjs input reset


【解决方案1】:

您没有正确地将状态数据传递给孩子,在将data 传递给孩子时,您应该这样做,

<CustomInput data={this.state.value} type="numeric" callbackParent={handleCustomInputValueChange} />

编辑:让您的孩子监听道具的变化,基于此设置状态值。

或者您可以将您的子渲染更改为:

 render() {
  const {data}   = this.props
        return <input type="text" onChange={this.handleChange} value={data?data:''} />;
    }

【讨论】:

  • 对不起,我忘了说我已经把它保存成这样了let {value} = this.state;
猜你喜欢
  • 2014-08-06
  • 1970-01-01
  • 2022-08-07
  • 2016-10-23
  • 2020-10-14
  • 2015-02-21
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
相关资源
最近更新 更多