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
            })
        }
  • 相关阅读:
    微信JS SDK Demo
    微信JS SDK使用权限签名算法
    微信JS接口
    微信分享JS接口失效说明及解决方案
    微信支付开发(2) 扫码支付模式一
    不懂技术的人不要对懂技术的人说这很容易实现
    独立开发者经验分享
    微信公开课PRO版张小龙演讲全文
    RC4加密算法的原理及实现
    上传APP加入视频预览--精简点名
  • 原文地址:https://www.cnblogs.com/finnlee/p/13636437.html
Copyright © 2011-2022 走看看