简体   繁体   English

反应-重置组件输入

[英]React - Reset component input

I am having a hard time with a component and I am hoping that you guys will help me out. 我在组件方面遇到了麻烦,希望你们能帮助我。 So I created a custom component that returns a formatted value of what the user typed in the input (if the user typed '1999-9-9', it returns '1999-09-09 00:00'), and the value is assigned to the state of the parent (handleCustomInputValueChange). 因此,我创建了一个自定义组件,该组件返回用户在输入中键入的格式值(如果用户键入“ 1999-9-9”,则返回“ 1999-09-09 00:00”),并且该值是分配给父状态(handleCustomInputValueChange)。 Now.. the problem is that if I click on the 'numeric' type and I fill the input with random characters, save it and the go to 'datetime', the input remains unchanged, it doesn't reset or it doesn't get the data from props. 现在..问题是,如果我单击“数字”类型,并用随机字符填充输入,将其保存并转到“ datetime”,则输入保持不变,不会重置或不会从道具获取数据。 It has the old value from the 'number'. 它具有“数字”中的旧值。 Using componentWillReceiveProps() method, in many case would be the answer to this problem, but not here, because all I want is to send the data to the parent. 使用componentWillReceiveProps()方法,在许多情况下将是此问题的答案,但在这里不是,因为我想要的只是将数据发送给父级。 I don't need that data to be sent back to my 'CustomInput'. 我不需要将数据发送回“ CustomInput”。

Parent component: 父组件:

    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;
    }

Child component 子组件

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} />;
    }
}

So.. is there any way to reset the input after switching to another type? 所以..在切换到另一种类型之后,有什么方法可以重置输入吗?

Thanks! 谢谢!

You are not passing the state data to the child properly, While passing the data to the child, you should do , 您没有将状态数据正确地传递给孩子,在将data传递给孩子时,您应该这样做,

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

Edit: Make your child listen for change in props, based on this set the state value. 编辑:基于此设置状态值,让您的孩子听道具变化。

Or you can change your child render to this: 或者,您可以将孩子的渲染更改为此:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM