在点击时更改背景颜色React Native。

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

change background color on click react native

问题

我想让我的按钮从白色更新背景颜色到蓝色,再次单击时,我希望将背景颜色设置为白色。如何从样式表中实现这个目标?如果不行,我应该如何做?

按钮:

<TouchableOpacity style={styles.circular}></TouchableOpacity>

样式:

circular: {
    width: 15,
    height: 15,
    borderColor: '#55bcf6',
    borderRadius: 5,
    borderWidth: 3,
    backgroundColor: 'white'
}
英文:

i want to make my button update its background color from white to blue and when i click again i want to make the background white again. how can is it possible to do this from the stylesheet? if not how can i do this

button:

&lt;TouchableOpacity style = {styles.circular}&gt;&lt;/TouchableOpacity&gt;

style:

circular:{
    width:15,
    height:15,
    borderColor:&#39;#55bcf6&#39;,
    borderRadius:5,
    borderWidth:3,
    backgroundColor:&#39;white&#39;
},

答案1

得分: 1

尝试添加一个 onClick 属性、一个颜色状态和一个动态样式,类似于以下方式:

const [color, setColor] = useState("white");

<TouchableOpacity
    onPress={() => setColor(color === 'blue' ? 'white' : 'blue')}
    style={{backgroundColor: color}}
>
</TouchableOpacity>
英文:

Try adding an onClick attribute, a color state and a dynamic style, something like this:

const [color, setColor] = useState(&quot;white&quot;);

&lt;TouchableOpacity
    onPress={() =&gt; setColor(color === &#39;blue&#39; ? &#39;white&#39; : &#39;blue&#39;)}
    style={{backgroundColor: color}}
&gt;
&lt;/TouchableOpacity&gt;

答案2

得分: 1

翻译结果如下:

使用[]的样式

const [color, setColor] = useState("white");

<TouchableOpacity
    onPress={() => setColor(color==='blue' ? 'white' : 'blue')}
    style={[styles.circular, {backgroundColor: color}]}
>
</TouchableOpacity>
英文:

using [] in style

const [color, setColor] = useState(&quot;white&quot;);

 &lt;TouchableOpacity
      onPress={() =&gt; setColor(color===&#39;blue&#39; ? &#39;white&#39; : &#39;blue&#39;)}
         style={[styles. circular, {backgroundColor: color}]}
 &gt;
 &lt;/TouchableOpacity&gt;

答案3

得分: 0

你可以在那里更改背景颜色并将其应用于默认值:

const [color, setColor] = useState("white");

<TouchableOpacity
  onPress={() => setColor(color === 'blue' ? 'white' : 'blue')}
  style={{ ...styles.circular, backgroundColor: color }}
>
</TouchableOpacity>
英文:

there you can you change the background Color and apply it with the default

const [color, setColor] = useState(&quot;white&quot;);

 &lt;TouchableOpacity
      onPress={() =&gt; setColor(color===&#39;blue&#39; ? &#39;white&#39; : &#39;blue&#39;)}
         style={{...styles.circular, backgroundColor: color}}
 &gt;
 &lt;/TouchableOpacity&gt;

huangapple
  • 本文由 发表于 2023年2月24日 05:42:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550619.html
匿名

发表评论

匿名网友

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

确定