React module methods with passing props to child or invoking callback to parent.

Some code samples for this pupose:

import React from "react";
import MyDemo from "./mydemo.jsx";

export default class Square extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
    this.handleChange = this.handleChange.bind(this);
    this.changeMyStateFromChild = this.changeMyStateFromChild.bind(this);
  }
  componentDidMount() {
    let me = this;
    me.setState({
      count: me.state.count + 1
    });
    console.log(me.state.count); // 打印出0
    me.setState({
      count: me.state.count + 1
    });
    console.log(me.state.count); // 打印出0
    setTimeout(function() {
      me.setState({
        count: me.state.count + 1
      });
      console.log(me.state.count); // 打印出2
    }, 0);
    setTimeout(function() {
      me.setState({
        count: me.state.count + 1
      });
      console.log(me.state.count); // 打印出3
    }, 0);
  }
  handleChange(e) {
    let me = this;
    const target = e.target;
    console.log(me);
    alert(me.state.count);
    this.setState({
      [target.name]: target.value
    });
    console.log(MyDemo);
  }
  changeMyStateFromChild(state) {
    // this.setState(state);
    debugger;
    alert(state);
  }
  render() {
    return (
      <div onChange={e => this.handleChange(e)}>
        <MyDemo
          title={this.state.count}
          changeParent={this.changeMyStateFromChild}
        />
        <input type="text" name="username" />
        <input type="text" name="password" />
        <button onClick={() => alert(MyDemo.title)}>click </button>
        <h1>{this.state.count}</h1>
      </div>
    );
  }
}
View Code

 

posted @ 2018-05-11 23:30  calochCN  阅读(99)  评论(0编辑  收藏  举报