ReactNative开发——组件的引用

前端之家收集整理的这篇文章主要介绍了ReactNative开发——组件的引用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

ReactNative开发——组件的引用

定义组件的引用

  1. <TextInput ref='aReferName'
  2. ...

使用组件

根据引用调用组件的方法

  1. this.refs.aReferName.公开函数()

示例

  1. render() { return ( <View style={{flex: 1,justifyContent: 'flex-start'}}> <TextInput ref='et' //设置该组件的引用为 et style={styles.textInputStyle} /> <TextInput style={{height: 80,margin: 10}} /> {/*通过组件的引用,调用组件的公开成员函数*/} <Button title="点击让第一个TextInput获取焦点" onPress={() => this.refs.et.focus()}/> </View> ); }

上面代码实现了:点击按钮,让第一个TextInput组件获取焦点的效果

获取组件的位置信息

每个ReactNative组件都已个measure成员函数,用来获取组件的位置信息。
示例:

  1. export default class Project07 extends Component {
  2.  
  3. componentDidMount() {
  4. // window.setTimeout(this.tempFunc.bind(this),1);
  5. // 使用箭头函数可以绑定this
  6. window.setTimeout(() => {
  7. this.refs.et.measure(this.getTextInputPosition)
  8. },1)
  9.  
  10. }
  11.  
  12. /** * 组件的位置信息回调 * */
  13. getTextInputPosition(fx,fy,width,height,px,py) {
  14. console.log('Component width is ' + width);
  15. console.log('Component height is ' + height);
  16. console.log('X offset to frame: ' + fx);
  17. console.log('Y offset to frame: ' + fy);
  18. console.log('X offset to page: ' + px);
  19. console.log('Y offset to page: ' + py);
  20. }
  21.  
  22. tempFunc() {
  23. this.refs.et.measure(this.getTextInputPosition)
  24. }
  25.  
  26. render() {
  27. return (
  28. <View style={{flex: 1,justifyContent: 'flex-start'}}> <TextInput ref='et' //设置该组件的引用为 et style={styles.textInputStyle} /> <TextInput style={{height: 80,margin: 10}} /> {/*通过组件的引用,调用组件的公开成员函数*/} <Button title="点击让第一个TextInput获取焦点" onPress={() => this.refs.et.focus()}/> </View> ); } }

猜你在找的React相关文章