如何避免重新渲染文本输入?



我有一个TextInput,我不希望每次我改变它里面的值时它都重新渲染

const [WrittenVal,setWrittenVal] = useState(()=>'');
...
<TextInput
value={String(WrittenVal)}
onChangeText={text => setWrittenVal(text)}
/>

我希望能够在按下按钮时改变输入内的值这就是为什么我没有使用defaultValue

任何解决方案? ?

const inputRef = useRef();
<TextInput
ref={inputRef}
onChangeText={text => inputRef.text = text }
/>

//function to get input value
const handleSubmit = () => {
let textInputValue = inputRef.text;
}

您可以使用useRef来保存文本输入而不呈现文本,并且使用useState来在按下按钮时显示输入文本:

实例:https://snack.expo.dev/TW-fMx1-2

import React from "react";
import { SafeAreaView, StyleSheet, TextInput,TouchableOpacity,Text } from "react-native";
const UselessTextInput = () => {
const [text, onChangeText] = React.useState("");
const textRef = React.useRef('')
const textToRef = (text) =>{
textRef.current = textRef.current + text
}
const showTextInInput = () =>{
onChangeText( textRef.current )
}
console.log("render")
return (
<SafeAreaView>
<TextInput
style={styles.input}
onChangeText={textToRef}
value={text}
/>
<TouchableOpacity onPress={showTextInInput}>
<Text>SHOW TEXT IN INPUT</Text>
</TouchableOpacity>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
input: {
height: 40,
margin: 12,
borderWidth: 1,
marginTop:50,
padding: 10,
},
});
export default UselessTextInput;

如果你有一个嵌套的组件情况,就像下面这样,你需要将状态移动到组件中(在EpicComponent下),settwrittenval将触发对EpicComponent的重新渲染。常见的症状是键入时字段将失去焦点。

const Parent = ()=> {
const [WrittenVal,setWrittenVal] = useState(()=>'');
...
const EpicComponent = ()=> {
return (   
<TextInput
value={String(WrittenVal)}
onChangeText={text => setWrittenVal(text)}
/> )
}
return (<EpicComponent/>)
}

你不能阻止字体的重新渲染。但是您的代码可以简化为:

const [value, setValue] = useState('');
<TextInput
value={value}
onChangeText={setValue}
/>

当值改变时,你不能阻止重新渲染。

但是你可以防止其他组件被React.memouseMemo钩子重新渲染。

通过按下按钮来改变输入值,你可以这样做:

<Button onPress={() => {
setWrittenVal(""); //write value you want in ""
}}

通过这样做,既可以防止重新呈现,又可以在单击按钮后重置文本输入值。


const ref = useRef("");
const inputRef = useRef(null);
const onChangeText = (item) => {
ref.current = item;
};
const addComment = async () => {
ref.current = "";
inputRef.current?.clear();
// Perform any other actions or logic you need here
};
return (
<View>
<TextInput ref={inputRef} onChangeText={onChangeText} />
<TouchableOpacity onPress={addComment}>
<Text>Send</Text>
</TouchableOpacity>
</View>
);

只能使用UseRef来防止重新渲染。const keyRef = useRef();

const keyToRef = (text)=>{
keyRef.text = text
}
<TextInput 
ref={keyRef}
onChangeText={keyToRef}
value={keyRef?.text}
/>

最新更新