非受控制组件和受控组件

192 阅读1分钟

一:非受控组件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
    <title>非受控组件</title>
</head>
<body>
    
<div id="box"></div>

<script type="text/babel">

    class MyComponent extends React.Component{
        render() {
            return (
                <div>
                    <input ref={this.input} type="text" placeholder="输入内容"/>
                    <button onClick={this.handleBtn1}>按钮1</button> 

                    <input onBlur={this.handleBtn2} type="text" placeholder="失去焦点"/>   
                </div>
            )
        }
        
        input = (currentNode) => {
            this.input1 = currentNode
        }

        handleBtn1 = () => {
            console.log('handleBtn1==',this.input1.value)
        }

        handleBtn2 = (event) => {
            console.log('event:',event.target.value)
        }


    }

    ReactDOM.render(<MyComponent/>,document.getElementById('box'))

</script>
</body>
</html>

注意:

  • 直接从节点上获取内容的
  • 不受组件的状态的控制

二:受控组件


<script type="text/babel">

    class MyComponent extends React.Component{
        state = {
            my_inputval: ""
        }
        render() {
            console.log('触发render')
            return (
                <div>
                    <input onChange = {this.input1} type="text" placeholder="输入内容"/>
                    <button onClick={this.handleBtn1}>按钮1</button> 
                </div>
            )
        }
        
        input1 = (event) => {
            // 把值存在组件的状态里
           this.setState({
            my_inputval: event.target.value
           })
        }

        handleBtn1 = () => {

            // 从组件的状态中获取
            let {my_inputval} = this.state
            console.log('handleBtn1==',my_inputval)
        }

    }

    ReactDOM.render(<MyComponent/>,document.getElementById('box'))

</script>

注意:

  • 不是通过ref获取值得,而是通过回调函数的参数Event获取值后,存在组件的state状态中,在需要的时候,从组件的状态中取值