简体   繁体   English

React Native-通过按键更改组件样式

[英]React Native - change component style by 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. 我知道在htmljavascript中,可以通过idclass更改其自己的css样式,在react native中,如何设置/更改组件样式。 I have map a list of component, and each of them have set a key value. 我已经map了一个组件列表,并且每个组件都设置了一个key When I call a function, I would like to change one of the component style. 调用函数时,我想更改一种组件样式。

eg: change the key is 2 component style 例如:更改key为2组件样式

_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 否则,您应该在组件中设置状态并更改状态以更新样式

eg 例如

first set ref to the component : 首先将ref设置为组件:

<SpecialItem 
    key={i}
    ref={(thisItem) => this[`item-${i}`] = thisItem}
/>

then setNativeProps : 然后setNativeProps:

_ChangeStyle() {
    this['item-2'].setNativeProps({style: {/* your style here */}});
}

full example 完整的例子

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>
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM