React Native - 按键更改组件样式 [英] React Native - change component style by key
问题描述
我知道在 html
和 javascript
中可以通过 id
和 css
改变它自己的 css
样式code>class ,在 react native 中,如何设置/更改组件样式.我有 map
一个组件列表,每个组件都设置了一个 key
值.当我调用一个函数时,我想改变一个组件样式.
I know that in html
and javascript
are able to change it own css
style by id
and class
, in react native, how to set / change the component style. I have map
a list of component, and each of them have set a key
value. When I call a function, I would like to change one of the component style.
例如:将key
更改为2个组件样式
eg: change the key
is 2 component style
_RenderSpecialItem(){
return this.state.speciallist.map((item, i)=>{
return(
<SpecialItem
key={i}
/>
);
});
}
_ChangeStyle(){
//do something
}
推荐答案
您可以使用 直接操作 但这不是一个好习惯,更多请阅读
You can use Direct Manipulation but it's not a good practice, for more please read
直接操作不会是您经常使用的工具;您通常只会使用它来创建连续动画以避免渲染组件的开销......
Direct manipulation will not be a tool that you reach for frequently; you will typically only be using it for creating continuous animations to avoid the overhead of rendering the component ...
在链接中.否则,您应该在组件中设置状态并更改状态以更新样式
in the link. Otherwise, you should you set state in component and change state to update the style
例如
首先将引用设置为组件:
first set ref to the component :
<SpecialItem
key={i}
ref={(thisItem) => this[`item-${i}`] = thisItem}
/>
然后设置NativeProps:
then setNativeProps :
_ChangeStyle() {
this['item-2'].setNativeProps({style: {/* your style here */}});
}
完整示例
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
speciallist: ['aaa', 'bbb', 'ccc']
}
}
componentDidMount() {
this['text-0'].setNativeProps({style: {fontSize: "10"}});
this['text-1'].setNativeProps({style: {fontSize: "20"}});
this['text-2'].setNativeProps({style: {fontSize: "30"}});
}
render() {
return (
<View style={styles.container}>
{
this.state.speciallist.map((item, i)=>(
<Text
key={`text-${i}`}
ref={(thisItem) => this[`text-${i}`] = thisItem}
>
{item}
</Text>
))
}
</View>
);
}
}
这篇关于React Native - 按键更改组件样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!