在ClearTextOnFocus之后,react-native重置TextInput

时间:2017-10-06 17:30:32

标签: react-native

我正在React-Native中构建一个表单,并将ClearTextOnFocus设置为true,因为它更容易处理动态格式化以进行编辑。

我试图通过将所有本地状态设置为redux存储来添加重置功能,但如果用户未在选定的TextInput中键入任何内容,则本地状态未更改,并且本机状态不会重新呈现的TextInput;把它留空。

任何人都对如何清除TextInput或强制React重新渲染有任何想法。代码是一项正在进行的工作,但这里有相关内容。

由于

class GoalScreen extends Component {

  componentWillMount = () => this.setPropsToState();

  onReset = () => {
    this.setPropsToState();
  }

  onChange = text => this.setState({ [text.field]: text.input });

  setPropsToState = () => {
    const { name } = this.props.goal;
    this.setState({ name });
  };


  render() {
    const { name } = this.state;

    return (
      <View style={styles.screenContainer}>

        <Text style={styles.text}> Name </Text>
            <TextInput
              placeholder="a brand new bag"
              keyboardType="default"
              autoCorrect={false}
              style={styles.inputField}
              clearTextOnFocus
              onChangeText={text => this.onChange({ input: text, field: 'rate' })}
              value={name}
              />
          </View>

  }
}

1 个答案:

答案 0 :(得分:0)

所以,我没有使用Redux,我的用例可能与你的用例有点不同,但我认为我的解决方案可能仍然适用于此,如果只是为了确认(经过几个小时的争论)它会出现将true传递给clearTextOnFocus prop会阻止对TextInput组件的进一步更新。

我尝试了所有可以想象的解决方法(比如setNativeProps(),forceUpdate())但没有任何效果,所以我最终必须编写自己的逻辑来清除和重置输入文本。

此组件应该1)清除焦点上的输入文本然后2)如果用户没有按下键,则将其重置为之前的值:

class ResettableInput extends Component {
  state = {
    Current: this.props.value,
    Previous: ""
  };

  KeyPressed = false;

  //cache current input value for later revert if necessary, and clear input
  onFocus = () => {
    this.setState({ Previous: this.state.Current, Current: "" });
  };

  //record whether key was pressed so input value can be reverted if necessary
  onKeyPress = () => {
    this.KeyPressed = true;
  };

  onChangeText = text => {
    this.setState({ Current: text });
  };

  //if no key was pressed, revert input to previous value
  onBlur = () => {
    if (!this.KeyPressed) {
      this.setState({ Current: this.state.Previous, Previous: "" });
    }
  };

  render = () => {
    return (
      <TextInput
        onChangeText={this.onChangeText}
        value={this.state.Current}
        onBlur={this.onBlur}
        onFocus={this.onFocus}
        onKeyPress={this.onKeyPress}
      />
    );
  };
}