如何使用ref属性来改变react-native element css样式

时间:2016-01-28 02:27:27

标签: react-native

我想传递ref属性来指定react-native元素并稍后更改css样式,

然而,我甚至无法从this.refs.[name]方法获取元素,如下面的代码。

<Text ref='foo' onPress={this._onPressText}>
  some text
</Text>

和回调方法,

_onPressText: function() {
  console.log(this.refs.foo);  // log undefine here
}

我该怎么办?

感谢..

1 个答案:

答案 0 :(得分:1)

如果您想通过其引用来操纵组件的样式,则可以这样实现:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textRef = React.createRef();
    this._onPressText = this._onPressText.bind(this);
  }

  _onPressText() {
    // Note: we're accessing "current" to get the DOM node
    console.log(this.textRef.current);
    
    //To change the css style of the component
    this.textRef.current.setNativeProps({
    style:{
    textDecorationLine: 'underline'
    }
    })
  }

  render() {
    // tell React that we want to associate the <text> ref
    // with the `textRef` that we created in the constructor
    return ( <
      div >
      <
      Text ref = 'foo'
      onPress = {
        this._onPressText
      } >
      some text <
      /Text> /
      div >
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

希望这会有所帮助