React组件proptypes, ref

一、使用props.children访问嵌套数据

import React from 'react';

class Button extends React.Component {
    render () {
        return (
            <Element>I <Like /> React</Element>
        )
    }
}
const Element = (props) => 
    <button>{ props.children }</button>

class Like extends React.Component {
    render () {
        return (
            <span> &hearts; </span>
        )
    }
}

export default Button;

通过props.children不仅拿到了自身的文本,而且拿到了<Like>中的内容。

二、自定义propTypes验证子组件props

import React from 'react';

class Check extends React.Component {
    render () {
        return (
            <Title />
        )
    }
}

const Title = (props) => 
    <h2>the Title: { props.title }</h2>

Title.propTypes = {
    title(props, propName,component) {
        // 验证是否为空
        if (!(propName in props)) {
            return new Error(`missing ${propName}`)
        }
        // 验证属性值的长度
        if (props[propName].length < 6) {
            return new Error(`the ${propName} is too short.`)
        }
    }
}

export default Check

 

 对代码做如下修改:

 即可消除报错信息。

2. 类型校验

 上述代码运行后会报错

 代码修改:

 报错消失。

如果是类声明组件,使用下面的代码进行验证:

class Element extends React.Component {
     const propTypes = {
        color: PropTypes.String.isRequired
     }
      //........
}

 四、默认props值 defaultProps

 上述代码不会产生报错,因为设置了defaultProps.

五、ref获取特定组件的引用

下面定义了两个span,想要分别对应两个不同的<input />标签中的内容。

import React from 'react';
import ReactDOM from 'react-dom'

class Twins extends React.Component {
    constructor () {
        super();
        this.state = {
            a: '',
            b: ''
        }
    }
    update (e) {
        this.setState({
            a: ReactDOM.findDOMNode(this.a).value,
            b: ReactDOM.findDOMNode(this.b).value
        })
    }

    render () {
        return (
            <div>
                <Input
                ref={component => this.a = component}
                update={this.update.bind(this)} />
                <span>{this.state.a}</span> 
                <hr></hr>
                <Input
                ref={component => this.b = component}
                update={this.update.bind(this)} />
                <span>{this.state.b}</span>
            </div>
        )
    }
}

class Input extends React.Component {
    render () {
        return (
            <input type='text' onChange={this.props.update} />
        )
    }
}
export default Twins

注意:这里Input一定要以class形式定义。

方法二:constructor中声明容器对象 

this.myRef = React.createRef();

将其赋给特定对象。由于react自身的机制,接受ref的组件会把自己添加到容器中。

<AddForm ref={this.myRef} />

通过this.myRef.current即可获取特定子组件中的属性。

posted @ 2020-04-01 10:58  cecelia  阅读(327)  评论(0编辑  收藏  举报