【问题标题】:Avoid TextInput re render on text change避免 TextInput 在文本更改时重新呈现
【发布时间】:2021-06-16 00:58:23
【问题描述】:

我有一个简单的 TextInput 和一个提交按钮,我想在不重新渲染组件的情况下处理文本更改。在类组件上,我使用私有变量“textContent”触发 OnChangeText 事件而不是状态来防止强制呈现,但我不知道如何使用函数组件来做到这一点。是否可以在函数组件上存储没有状态的文本值?谢谢

这是组件(在文本更改时重新呈现):

const Search = () => {
    const [_films, setFilms] = useState([]);
    const [_text, setText] = useState('');

    const _loadFilms = () => {
        console.log(_text);
        if (_text.length > 0) {
            getFilmsFromApiWithSearchedText(_text).then(data => {
                setFilms(data.results);
            });
        }
    }
    
    console.log("rendering");

    return (
        <View style={styles.main_container}>
            <TextInput style={styles.textinput} placeholder='Titre du film' onChangeText={(text) => setText(text)} />
            <Button title='Rechercher' onPress={() => { _loadFilms() }} />
            <FlatList
                data={_films}
                keyExtractor={(item) => item.id.toString()}
                renderItem={({ item }) => <FilmItem film={item} />}
            />
        </View>
    );
}

const styles = StyleSheet.create({
    main_container: {
        flex: 1,
        marginTop: 20
    },
    textinput: {
        marginLeft: 5,
        marginRight: 5,
        height: 50,
        borderColor: '#000000',
        borderWidth: 1,
        paddingLeft: 5
    }
});

export default Search;`

【问题讨论】:

    标签: react-native


    【解决方案1】:

    在类组件上,您可以将文本存储在类的私有变量中。使用功能组件,您可以将 refs 用于等效的东西。有关如何操作的更多信息,请参阅this SO question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 2019-01-28
      • 2020-09-14
      • 2019-01-09
      • 2021-01-26
      相关资源
      最近更新 更多