如何重设作为自定义组件的TextInput?

时间:2019-02-09 15:01:49

标签: reactjs react-native

大家好,我有一个用于TextInput的自定义组件,提交表单后,我想重置该字段,但似乎没有进行任何更改。

这是在我的渲染器中导入的组件;

<InputField
    customStyle={{ marginBottom: 30, marginTop: 20 }}
    textColor={colors.black}
    labelText="JOB TITLE"
    labelTextSize={14}
    labelColor={colors.black}
    borderBottomColor={borderColor}
    inputType="text"
    multiline={true}
    onChangeText={this.handleNameChange}
    showCheckmark={validName}
/>

现在onChangeText函数与此相关

handleNameChange(name) {
    const { validName } = this.state;
    this.setState({ name });
    if (!validName) {
      if (name.length >= 10) {
        this.setState({ validName: true });
      }
    } else if (name.length < 10) {
      this.setState({ validName: false });
    }
  }

这是我实际的TextInput实现

onChangeText(text) {
   this.props.onChangeText(text);
   this.setState({ inputValue: text });
}

<TextInput
      style={[
        { color: inputColor, borderBottomColor: borderBottom },
        inputStyle,
        styles.inputField
      ]}
      secureTextEntry={secureInput}
      onChangeText={this.onChangeText}
      keyboardType={keyboardType}
      autoFocus={autoFocus}
      autoCorrect={false}
      underlineColorAndroid="transparent"
      placeholder={placeholder}
      defaultValue={inputValue}
      value={inputValue}
      editable={editable}
      multiline={multiline}
    />

因此,我想在提交表单时重置字段。我已经尝试过setState({name: ""}),它正在更改渲染中的状态,但没有从名为inputValue

的组件中更改状态

1 个答案:

答案 0 :(得分:0)

由于不会自动清除值的状态,因此它将保持不变。您需要在TextInput的值上使用setState。所以像this.setState({inputValue:''})这样的东西应该起作用。