【问题标题】:react-native reseting TextInput after ClearTextOnFocus在 ClearTextOnFocus 之后反应原生重置 TextInput
【发布时间】:2017-10-06 17:30:32
【问题描述】:

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

我正在尝试通过将所有本地状态设置为 redux 存储来添加重置功能,但是如果用户没有在选定的 TextInput 中键入任何内容,则本地状态没有改变,并且 react native 不会重新渲染文本输入;留空。

任何人都对我如何清除 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>

  }
}

【问题讨论】:

  • 我认为你的 onChangeText 属性可能是一个内联函数,如果是这样你应该考虑重写它(见cdb.reacttraining.com/…

标签: react-native


【解决方案1】:

所以,我没有使用 Redux,我的用例可能与你的有点不同,但我认为我的解决方案在这里可能仍然相关,如果只是为了确认(经过数小时的争论)它出现了将 true 传递给 clearTextOnFocus 属性会阻止对 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}
      />
    );
  };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多