|

React Refs添加一个组件的引用

React 支持一种非常特殊的属性 Ref ,你可以用来绑定到 render() 输出的任何组件上。

这个特殊的属性允许你引用 render() 返回的相应的支撑实例( backing instance )。这样就可以确保在任何时间总是拿到正确的实例。

这种特性,让我想到了jquery中的$符号。虽然两者有本质的区别的,但起到的作用,好像是一样的。

使用方法

绑定一个 ref 属性到 render 的返回值上:

<input ref="myInput" />

在其它代码中,通过 this.refs 获取支撑实例:

var input = this.refs.myInput; var inputValue = input.value; var inputRect = input.getBoundingClientRect();

下面是一个具体的例子:

import React, { Component } from 'react';

class LikeButton extends Component {
    constructor(props) {
        super(props);

        // 设置 initial state
        this.state = {
            liked: { liked: false }
        };

        // ES6 类中函数必须手动绑定
        this.handleClick = this.handleClick.bind(this);
    }
    componentWillMount() {
        console.log('Component WILL MOUNT!在渲染前调用,在客户端也在服务端')
    }
    componentDidMount() {
        console.log('Component DID MOUNT!在第一次渲染后调用,只在客户端')
    }
    componentWillReceiveProps(newProps) {
        console.log('Component WILL RECEIVE PROPS!在组件接收到一个新的prop时被调用')
    }
    shouldComponentUpdate(newProps, newState) {
        console.log("shouldComponentUpdate返回一个布尔值。在组件接收到新的props或者state时被调用");
        return true;
    }
    componentWillUpdate(nextProps, nextState) {
        console.log('Component WILL UPDATE!在组件接收到新的props或者state但还没有render时被调用');
    }
    componentDidUpdate(prevProps, prevState) {
        console.log('Component DID UPDATE在组件完成更新后立即调用!')
    }
    componentWillUnmount() {
        console.log('Component WILL UNMOUNT在组件从 DOM 中移除的时候立刻被调用!')
    }
    handleClick(event) {
        this.setState({
            liked: !this.state.liked
        });
        this.refs.myInput.value = "哈哈,好用了!";
        // this.state = { liked: !this.state.liked };
    }
    render() {

        let text = this.state.liked ? '喜欢' : '不喜欢';
        return ( < div > < input type = "text"
            ref = "myInput" / > < button onClick = {
                this.handleClick
            } > {
                text
            } < /button></div > );
    }
}

export default LikeButton

类似文章