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
        })
    }
原文地址:https://www.cnblogs.com/finnlee/p/13636437.html