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
            })
        }
  • 相关阅读:
    博客第一天
    页码始终下沉
    让作为背景图片的图片显示,上面的文字消失
    select清除原来样式
    文章查看更多时的文字变淡效果
    ul去除项目符号并删除其所占空间
    添加下划线的两种方法
    js之数组操作
    js之argument小解
    腾讯云服务器搭建
  • 原文地址:https://www.cnblogs.com/finnlee/p/13636437.html
Copyright © 2011-2022 走看看