zoukankan      html  css  js  c++  java
  • React组件通讯

    1.子组件操作父组件值

    父组件代码:

    import React, { Component } from 'react'
    import Demo from './Demo'
    class Todo extends Component {
        constructor(){
            super();
            this.state = {
                title:'张三丰'
            }
        }
        addTodo = (title) =>{
            console.log(title)
            this.setState({
                title:title
            })
        }
        render() {
            return (
                <div>
                    我的名字叫:{this.state.title}
                    <Demo addTodo = {this.addTodo} />
                </div>
            )
        }
    }
    export default Todo

    子组件代码:

    import React, { Component } from 'react'
    
    
    class Demo extends Component {
        constructor(){
            super();
    
            this.state = {
                inputValue :'',
            }
        }
    
        handleInputValue = (e) =>{
            console.log(e.currentTarget.value);
            this.setState({
                inputValue:e.currentTarget.value
            })
        }
        handleAddBtn = () => {
            console.log(this.state)
            
            this.props.addTodo(this.state.inputValue)
        }
        render() {
            return (
                <div>
                    <input 
                        type="text" 
                        value={this.state.inputValue} 
                        onChange={this.handleInputValue}    
                    />
                    <button onClick={this.handleAddBtn} >点击</button>
                </div>
            )
        }
    }
    export default Demo;

     方法传值:

    this.handleInputValue.bind(this,123)

     通过ref获取组件或DOM,需先引入createRef方法来创建一个ref

    constructor(){
            super();
    
            this.state = {
                inputValue :'',
            }
    
            this.inputDom = createRef()  //创建
        }
    render() {
            return (
                <div>
                    <input 
                        type="text" 
                        value={this.state.inputValue} 
                        onChange={this.handleInputValue}
                        ref={this.inputDom}    //调用
                    />
                    <button onClick={this.handleAddBtn} >点击</button>
                </div>
            )
        }
     handleInputValue = (e) =>{
            console.log(e.currentTarget.value);
            this.setState({
                inputValue:e.currentTarget.value
            },()=>{
                this.inputDom.current.foucs() //操作DOM
            })
        }
  • 相关阅读:
    二分图那套理论
    洛谷P4351 [CERC2015]Frightful Formula【组合计数】
    「AGC023E」Inversions【组合计数】
    类欧几里得算法及其拓展
    OLAP 一些扯淡
    auto vectorized case shift
    备忘录
    lambda function pointer
    C++ atomic
    gdb 使用了 O0 但是还是有 <optimized out>
  • 原文地址:https://www.cnblogs.com/finnlee/p/13636437.html
Copyright © 2011-2022 走看看