【问题标题】:Is setting a value attribute in TextInput necessary?是否需要在 TextInput 中设置值属性?
【发布时间】:2020-06-24 01:53:48
【问题描述】:

我遇到了这样的问题(特别是在 TextInput 值属性中):

const Stuff = props => {
  const [items, setItems] = useState([]);

  const handleNewItem = () => {
    setItems([...items, '']);
  };

  const handleText = (text, index) => {
    items[index] = text;
    setItems(items);
    // this was populating correctly in console.log
    // as I type, it will come out like ["somedata", "blah"....] etc...
  };

  return (
    <>
      <View style={{marginTop: 20}}>
        <View>
          {items.map((items, index) => {
            return (
              <View key={index}>
                <Text>{index + 1}</Text>

                // issue with setting value attribute
                // Text would disappear as I type in the input field
                <TextInput value={items} onChangeText={text => handleText(text, index)} />

              </View>
            );
          })}
          <TouchableOpacity onPress={e => handleNewItem(e)}>
            <Text>Add item</Text>
          </TouchableOpacity>
        </View>
      </View>
    </>
  );
};

我能够让控制台注销items 的正确值,但在我的移动模拟器上,当我输入内容时,文本消失了。

当我从 TextInput 组件中删除 value={items} 时,我可以在模拟器输入字段中输入,而文本不会消失。我一直认为我们需要 reactjs 的价值。我们不需要这个吗?还是我做错了什么?

【问题讨论】:

    标签: reactjs react-native textinput


    【解决方案1】:

    我建议不要直接更新您的状态。而是使用新对象来更新状态,例如

    
      const handleText = (text, index) => {
        let newItems = [...items];
        newItems[index] = text;
        setItems(newItems);
      };
    
    

    【讨论】:

    • 这是有原因的吗?
    • 我不这么认为。在这篇文章中并没有真正回答我的主要问题=\
    • 建议在 textinput 中设置一个 value 属性。否则它将表现得像不受控制的组件。那可能会失去它的状态。
    猜你喜欢
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 2018-07-19
    • 2016-10-17
    • 2015-09-20
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多