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

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

Why the button is not disabling when there is no text?

问题

我是新手使用React Native,在创建我的应用时,无法使自动添加按钮禁用工作。

我设置了这些属性作为钩子:

  1. const [taskText, setTaskText] = useState(null);
  2. const [isDisabled, setDisabled] = useState('true');

然后我有我的函数:

  1. const addActivity = () => {
  2. if (taskText == null){
  3. setDisabled('true');
  4. }else{
  5. setDisabled('false');
  6. }
  7. }

但是当我在TouchableOpacity的disable属性上使用isDisabled时,它没有更新。

textInput属性:

  1. onChange={() => addActivity()}

TouchableOpacity:

  1. <TouchableOpacity style={styles.addWrapper} onPress={() => handleNewTask()} disabled={isDisabled}>
  2. <Text style={styles.addText}>+</Text>
  3. </TouchableOpacity>

setTaskText:(由TextInput调用)

  1. 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:

  1. const [taskText, setTaskText] = useState(null);
  2. const [isDisabled, setDisabled] = useState(&#39;true&#39;);

then i have my function:

  1. const addActivity = () =&gt; {
  2. if (taskText == null){
  3. setDisabled(&#39;true&#39;);
  4. }else{
  5. setDisabled(&#39;false&#39;);
  6. }
  7. }

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

textInput prop :

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

TouchableOpacity:

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

setTaskText: (called by TextInput)

  1. 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 更改为:

  1. const addActivity = () => {
  2. if (taskText == null){
  3. setDisabled(true);
  4. }else{
  5. setDisabled(false);
  6. }
  7. }
英文:

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 :

  1. const addActivity = () =&gt; {
  2. if (taskText == null){
  3. setDisabled(true);
  4. }else{
  5. setDisabled(false);
  6. }
  7. }

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:

确定