码迷,mamicode.com
首页 > 其他好文 > 详细

21.react 组件通信

时间:2018-08-12 17:23:43      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:efs   end   add   java   eve   int   type   map   rop   

状态属性可以修改

this.setState()中可以写对象,也可以写方法

<script type="text/babel">

class Test extends React.Component{
    constructor(...args){
        super(...args);
        this.state = {
            n:1
        }
    }
    fn(){
        /*this.setState({
            n:this.state.n+1
        });*/

        /*this.setState(function(prevState,props){
            console.log(prevState,props);
            return {
                n:prevState.n + 1
            }
        });*/
        this.setState((prevState,props)=>({n:prevState.n + 1}));
    }

    render(){
        return <div>
            <span>{this.state.n}</span>
            <input onClick={this.fn.bind(this)} type="button" value="按钮" />

        </div>
    }
}
ReactDOM.render(
    <Test name="abc"/>,
    document.getElementById("app")

);
</script>

res:
技术分享图片

事件:

获取点击坐标

<script type="text/babel">
class Test extends React.Component{
    constructor(...args){
        super(...args);
    }

    fn(ev){
        console.log(1,ev);
        console.log(2,ev.clientX,ev.clientY);
    }

    render(){
        return <div>
            <input onClick={this.fn.bind(this)} type="button" value="按钮" />

        </div>
    }
}

ReactDOM.render(
    <Test/>,
    document.getElementById("app")
);
</script>

res:
技术分享图片

事件冒泡:

没有ev.cancelBubble
用ev.stopPropagation();

<script type="text/babel">

class Test extends React.Component{
    constructor(...args){
        super(...args);
    }
    div(ev){
        alert("div");
    }
    btn(ev){
        //ev.cancelBubble = true;//X 没有这个属性
        //console.log( ev.cancelBubble );
        ev.stopPropagation();//√
        alert("btn");
    }

    render(){
        return <div onClick={this.div.bind(this)}>
            <input onClick={this.btn.bind(this)} type="button" value="按钮" />

        </div>
    }
}
ReactDOM.render(
    <Test/>,
    document.getElementById("app")
);
</script>

默认事件:

return false;//无效
用ev.preventDefault();

<script type="text/babel">
    class Test extends React.Component{
        constructor(...args){
            super(...args);
        }
        fn(ev){
            ev.preventDefault();
            //return false;
        }
    
        render(){
            return <div>
                <a onClick={this.fn.bind(this)} href="http://www.baidu.com/">百度</a>
            </div>
        }
    }
    
    ReactDOM.render(
        <Test/>,
        document.getElementById("app")
    );
</script>

留言板:

留言板添加删除

<script type="text/babel">
class Test extends React.Component{
    constructor(...args){
        super(...args);
        this.state={
            msg:"",
            arr:["aaa","bbb","ccc"],
        }
    }
    show(ev){
        this.setState({
            msg:ev.target.value,
        })
    }
    add(){
        this.state.arr.unshift(this.state.msg);
        this.setState({
            arr:this.state.arr
        })
    }
    del(index){
        this.state.arr.splice(index,1);
        this.setState({
            arr:this.state.arr
        })
    }

    render(){
        let arr = this.state.arr;
        /*let aULi = [];
        for(let i = 0; i < arr.length; i++){
            aULi.push(<li key={i}>{arr[i]}</li>);
        }*/
        let aUli = arr.map((item,index)=><li key={index}>{item}<a onClick={this.del.bind(this,index)} href="javascript:;">删除</a></li>);
        return <div>
            <input type="text" onInput={this.show.bind(this)}/>
            <input type="button" onClick ={this.add.bind(this)} value="添加"/>
            <ul>
                {aUli}
            </ul>
            
        </div>
    }
}
ReactDOM.render(
    <Test/>,
    document.getElementById("app"),
)
</script>

res:
技术分享图片
技术分享图片

数据绑定:

input数据绑定,加value属性时需要加onChange事件
this.setState({
msg:ev.target.value
});

<script type="text/babel">
class Test extends React.Component{
    constructor(...args){
        super(...args);
        this.state = {
            msg:"",
        }
    }

    fn(ev){
        this.setState({
            msg:ev.target.value
        });
    }
        
    render(){
        return <div>
            <input type="text" onInput={this.fn.bind(this)} /> <br />
            
            <input type="text" value={this.state.msg} onChange={this.fn.bind(this)} /> <br />
            {this.state.msg}
        </div>
    }
}
ReactDOM.render(
    <Test/>,
    document.getElementById("app")
);
</script>

res:
技术分享图片

求和:

exp1:

<script type="text/babel">
class Test extends React.Component{
    constructor(...args){
        super(...args);
        this.state = {
            a:1,b:1
        }
    }

    keyupHandle1(ev){
        this.setState({
            a:parseInt(ev.target.value),
        });
    }
    keyupHandle2(ev){
        this.setState({
            b:parseInt(ev.target.value),
        });
    }
    sumHandle(){

    }
 
    render(){
        return <div>
                <input type="text" onKeyUp={this.keyupHandle1.bind(this)} /> 
                <input type="text" onKeyUp={this.keyupHandle2.bind(this)} /> 
                <input onClick={this.sumHandle.bind(this)} type="button" value="=" />
                {this.state.a + this.state.b}
        </div>
    }
}

ReactDOM.render(
    <Test/>,
    document.getElementById("app")
);
</script>

res:
技术分享图片

exp2:

<script type="text/babel">
class Test extends React.Component{
    constructor(...args){
        super(...args);
        this.state = {
            a:1,b:1
        }
    }
    sumHandle(){
        let oText1 = document.getElementById("txt1");
        let oText2 = document.getElementById("txt2");
        this.setState({
            a:parseInt(oText1.value),
            b:parseInt(oText2.value)
        });
    }
 
    render(){
        return <div>
                <input id="txt1" type="text"  /> 
                <input id="txt2" type="text"   /> 
                <input onClick={this.sumHandle.bind(this)} type="button" value="=" />
                {this.state.a + this.state.b}
        </div>
    }
}

ReactDOM.render(
    <Test/>,
    document.getElementById("app")
);
</script>

res:
技术分享图片

exp3:

<script type="text/babel">
class Test extends React.Component{
    constructor(...args){
        super(...args);
        this.state = {
            a:1,b:1
        }
    }
    sumHandle(){

        console.log(this.refs);
        
        this.setState({
            a:parseInt(this.refs.txt1.value),
            b:parseInt(this.refs.txt2.value)
        });
    }
 
    render(){
        return <div>
                <input ref="txt1" type="text"  /> 
                <input ref="txt2" type="text"   /> 
                <input onClick={this.sumHandle.bind(this)} type="button" value="=" />
                {this.state.a + this.state.b}
        </div>
    }
}

ReactDOM.render(
   <div>
        <Test/>
        <Test/>
   </div>,
    document.getElementById("app")
);
</script>

技术分享图片

exp3:

<script type="text/babel">
class Test extends React.Component{
    constructor(...args){
        super(...args);
        this.state = {
            a:1,b:1
        }
    }

    keyupHandle1(ev){
        this.setState({
            a:parseInt(ev.target.value),
        });
    }
    keyupHandle2(ev){
        this.setState({
            b:parseInt(ev.target.value),
        });
    }
    render(){
        return <div>
                <input type="text" value={this.state.a} onChange={this.keyupHandle1.bind(this)} /> 
                <input type="text" value={this.state.b} onChange={this.keyupHandle2.bind(this)} /> 
                <input  type="button" value="=" />
                {this.state.a + this.state.b}
        </div>
    }
}

ReactDOM.render(
    <Test/>,
    document.getElementById("app")
);
</script>

res:
技术分享图片

==组件通信:==

父子:

父--->子

传递数据:props refs

子--->父

1、需要先把父级传递给子级

非父子 :需要借助全局变量 缺点:乱!不易管理!

exp1:父--->子
<script type="text/babel">
class Parent extends React.Component{
    constructor(...args){
        super(...args);
        this.state = {
            name:"你好呀!"
        }
    } 
    render(){
        return <div> 父组件 ----{this.state.name}
            <Child name={this.state.name}/>
        </div>
    }
}

class Child extends React.Component{
    constructor(...args){
        super(...args);
    } 
    render(){
        return <div>子组件----{this.props.name}</div>
    }
}
ReactDOM.render(
    <Parent/>,
    document.getElementById("app")
);
</script>

res:
技术分享图片

exp2: 子--->父

parent={this}把整个父元素传过去

<script type="text/babel">
class Parent extends React.Component{
    constructor(...args){
        super(...args);
        this.state = {
            name:"你好呀!"
        }
    }
    fn(data){
        alert("父级");
        this.setState({
            name:data
        })
    }
    render(){
        return <div> 父组件 ----{this.state.name}
            <Child name={this.state.name} parent={this} />
        </div>
    }
}

class Child extends React.Component{
    constructor(...args){
        super(...args);
    } 
    fn(){
        this.props.parent.fn(666);

    }

    render(){
        return <div onClick={this.fn.bind(this)}>子组件----{this.props.name}</div>
    }
}
ReactDOM.render(
    <Parent/>,
    document.getElementById("app")
);
</script>

res:
技术分享图片
技术分享图片
技术分享图片

exp3:父子通信显示删除
<script type="text/babel">

let arr = [
    {id:Math.random(),username:"aaa",password:"123"},
    {id:Math.random(),username:"bbb",password:"123"},
    {id:Math.random(),username:"ccc",password:"123"}
];
//父,列表
class UserList extends React.Component{
    constructor(...args){
        super(...args);
        this.state = {
            users:this.props.users
        }
    }  
    delHandle(id){
        //alert("删除"+id);

        this.setState({
            users:this.state.users.filter(item => id != item.id)
        });
    }

    render(){

        let aUser = this.state.users.map((item,index)=><User key={item.id} parent={this} user={item}/>);

        return <ul>
            {aUser}
        </ul>
    }
}
//子,元素
class User extends React.Component{
    constructor(...args){
        super(...args);
    }  
    fn(id){
        this.props.parent.delHandle(id);
    }
    render(){
        return <li>{this.props.user.username}-----{this.props.user.password} 

            <a onClick={this.fn.bind(this,this.props.user.id)} href="javascript:;">删除</a>

        </li>
    }
}

ReactDOM.render(
    <UserList users={arr}/>,
    document.getElementById("app")
);
</script>

res:
技术分享图片

技术分享图片

exp4:兄弟通信

点击组件2修改组件1,设置全局变量,

<script type="text/babel">
//全局变量
let a = null;
class Comp1 extends React.Component{
    constructor(...args){
        super(...args);
        this.state = {
            msg:"aaaa"
        }

        a=(data)=>{
            //alert(1);
            this.setState({
                msg:data
            });
        }
    }
    render(){
        return <div>组件1-----{this.state.msg}</div>
    }
}

class Comp2 extends React.Component{
    constructor(...args){
        super(...args);
    }
    fn(){
        a("bbb");
    }
    render(){
        return <div onClick={this.fn.bind(this)}>组件2</div>
    }
}

ReactDOM.render(
    <div>
        <Comp1/>
        <Comp2/>
    </div>,
    document.getElementById("app")
);
</script>

res:
技术分享图片
技术分享图片

21.react 组件通信

标签:efs   end   add   java   eve   int   type   map   rop   

原文地址:https://www.cnblogs.com/zhongchao666/p/9463043.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!