为什么按钮没有在没有文本时禁用?

huangapple go评论52阅读模式
英文:

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(&#39;true&#39;);

then i have my function:

const addActivity = () =&gt; {
    if (taskText == null){
      setDisabled(&#39;true&#39;);
    }else{
      setDisabled(&#39;false&#39;);
    }
  }

but when i use isDisabled on touchableOpacity's disable prop its not updating

textInput prop :

onChange={() =&gt; addActivity()}

TouchableOpacity:

&lt;TouchableOpacity style={styles.addWrapper} onPress={() =&gt; handleNewTask()} disabled={isDisabled}&gt;
    &lt;Text style={styles.addText}&gt;+&lt;/Text&gt;
&lt;/TouchableOpacity&gt;

setTaskText: (called by TextInput)

onChangeText={text =&gt; 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(&#39;true&#39;) 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 = () =&gt; {
    if (taskText == null){
      setDisabled(true);
    }else{
      setDisabled(false);
    }
  }

huangapple
  • 本文由 发表于 2023年2月7日 03:56:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365974.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定