2

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.

eg: change the key is 2 component style

_RenderSpecialItem(){
  return this.state.speciallist.map((item, i)=>{
    return(
      <SpecialItem 
        key={i}
      />
    );
  });
}

_ChangeStyle(){
  //do something
}
FeelRightz
  • 2,777
  • 2
  • 38
  • 73

1 Answers1

3

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

e.g.

first set ref to the component :

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

then 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>
    );
  }
}
Stanley Cheung
  • 929
  • 7
  • 22
  • getting this error `Cannot read property 'setNativeProps' of undefined` – FeelRightz Oct 20 '17 at 09:15
  • few things... have you use bind the function to the class and is the function run after rendering? I've updated a full example... you can check the `setNativeProps` in componentDidMount to change the style after rendering – Stanley Cheung Oct 20 '17 at 09:54
  • stil getting `Cannot read property 'setNativeProps' of undefined` – FeelRightz Oct 20 '17 at 10:26
  • 1
    hi, i try follow your changestyle function ,it gave me this error `TypeError: _this[("item-2")].setNativeProps is not a function` – FeelRightz Oct 27 '17 at 09:21
  • You're getting undefined most likely because `componentDidMount()` is called before `.map` has had time to execute. Adding a timer may help. – Mix Master Mike Apr 05 '19 at 22:54