英文:
Why the button is not disabling when there is no text?
问题
我是新手使用React Native,在创建我的应用时,无法使自动添加按钮禁用工作。
我设置了这些属性作为钩子:
const [taskText, setTaskText] = useState(null);
const [isDisabled, setDisabled] = useState('true');
然后我有我的函数:
const addActivity = () => {
if (taskText == null){
setDisabled('true');
}else{
setDisabled('false');
}
}
但是当我在TouchableOpacity的disable属性上使用isDisabled时,它没有更新。
textInput属性:
onChange={() => addActivity()}
TouchableOpacity:
<TouchableOpacity style={styles.addWrapper} onPress={() => handleNewTask()} disabled={isDisabled}>
<Text style={styles.addText}>+</Text>
</TouchableOpacity>
setTaskText:(由TextInput调用)
onChangeText={text => setTaskText(text)}
当我删除所有文本时,TextInput不会更新自身吗?我该怎么做才能解决这个问题?
英文:
I'm new to react-native and when i was creating my app i couldn't get auto add button disabling to work
I set up these properties as a hooks:
const [taskText, setTaskText] = useState(null);
const [isDisabled, setDisabled] = useState('true');
then i have my function:
const addActivity = () => {
if (taskText == null){
setDisabled('true');
}else{
setDisabled('false');
}
}
but when i use isDisabled on touchableOpacity's disable prop its not updating
textInput prop :
onChange={() => addActivity()}
TouchableOpacity:
<TouchableOpacity style={styles.addWrapper} onPress={() => handleNewTask()} disabled={isDisabled}>
<Text style={styles.addText}>+</Text>
</TouchableOpacity>
setTaskText: (called by TextInput)
onChangeText={text => setTaskText(text)}
Doesn't TextInput update itself when i delete all the text?
What do i do to fix this?
答案1
得分: 0
因为你使用了 useState('true')
,并且你在状态中始终使用字符串。当字符串不为空时,它始终为真。
你必须使用布尔值而不是字符串。因此,你可以更改为 useState(true)
,并将 addActivity
更改为:
const addActivity = () => {
if (taskText == null){
setDisabled(true);
}else{
setDisabled(false);
}
}
英文:
It is because you use : useState('true')
and you always use a string in your state.
A string, when it is not empty, is always true.
You must use the boolean values not string. You can therefore change to : useState(true)
and change addActivity
to :
const addActivity = () => {
if (taskText == null){
setDisabled(true);
}else{
setDisabled(false);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论