React组件渲染后对DOM的操作示例

文章目录

在React.js中基本不需要对DOM进行操作,可以直接通过 setState 的方式重新渲染组件,渲染的时候可以把新的 props 传递给子组件,从而达到页面数据更新的效果。

但是有的时候需要组件渲染完后对DOM进行一些操作,比如表单提交后对其中的<input>中的内容进行清空,重新定义鼠标焦点,下面以1个简单的例子进行说明。先看下显示效果:
在这里插入图片描述

在上例中,组件渲染结束后,清空了文本输入框中的内容,并重新把鼠标焦点focus在文本框中,React.js 提供了 ref 属性来帮助我们获取已经挂载的元素的 DOM 节点,你可以给某个 JSX 元素加上 ref属性(本例中给<input>加上了ref属性),这个ref属性值是一个回调函数。当 input 元素在页面上挂载完成以后,React.js 就会调用这个函数,并且把这个挂载以后的 DOM 节点传给这个函数。在函数中我们把这个 DOM 元素设置为组件实例的一个属性,这样以后我们就可以通过 this.input 获取到这个 DOM 元素。然后我们可以在setNewColor()函数中调用this.input.value和this.input.focus,实现清空文本框输入内容,重新focus鼠标焦点的操作。

关键代码如下:给<input>增加ref属性,这样通过this.input获取input这个DOM元素,并调用相应的API。

<input
  ref={
    
    (input) => this.input = input}
  placeholder={
    
    "Please enter a color"}
  onChange={
    
    e => this.colorValue(e)}
/>

完整代码如下:

class Color extends React.Component {
    
    
    constructor(props) {
    
    
        super(props);
        this.state = {
    
    
            color: '',
            bgColor: ''
        };
    }

    //获取文本框中用户输入的内容
    colorValue(e) {
    
    
        this.setState({
    
    
                color: e.target.value
            }
        );
    }

    //点击按钮后事件
    setNewColor(e) {
    
    
        this.setState({
    
    
            bgColor: this.state.color
        });

        //设置完背景颜色后,清空输入框内容,重新获得焦点
        this.input.value = "";
        this.input.focus();

        //阻止默认行为
        e.preventDefault();
    }

    render() {
    
    
        const squareStyle = {
    
    
            //如果是this.state.color,直接显示颜色,不需要点击show按钮
            backgroundColor: this.state.bgColor,
        };


        return (
            <div className={
    
    "colorArea"}>
                <div className={
    
    "colorSquare"} style={
    
    squareStyle}></div>
                <form onSubmit={
    
    e => this.setNewColor(e)}>
                    <input
                        ref={
    
    (input) => this.input = input}
                        placeholder={
    
    "Please enter a color"}
                        onChange={
    
    e => this.colorValue(e)}/>
                    <button type={
    
    "submit"}>show</button>
                </form>
            </div>
        );
    }
}


if (document.getElementById('container')) {
    
    
    ReactDOM.render(
        <div>
            <Color/>
        </div>,
        document.getElementById('container')
    );
}

猜你喜欢

转载自blog.csdn.net/qq_34307801/article/details/88547905
今日推荐