React学习(三)-组件使用

一.组件

  React可以将模块拆分为多个组件,用分而治之的思想,让各个组件专注于实现某个功能。在设计上,符合高内聚、低耦合原则。高内聚是组件内部实现自己的逻辑,像展示页面的jsx,定义行为的js,甚至是样式css。低耦合是,各个组件相互依赖关系要弱化,每个组件尽量独立。

二.组件交互

   定义一个Home组件。

var React = require('react');

class Home extends React.Component {
    constructor(props) {
        super(props);
        //定义数据
        this.state = {
            text: "this is home"
        };
    }

    render() {
        return <div>
            {this.state.text}
        </div>;
    }
}

export default Home;

   在其它组件中引用Home组件。

var React = require('react');
import Home from './component/Home.jsx'

class App extends React.Component {
    constructor() {
        super();
        //定义数据
        this.state = {
            text: "hello world"
        };
    }

    render() {
        return <div>
            <Home></Home>
        </div>;
    }
}

export default App;

  这样子输出页面就可以看到Home组件的内容。那组件间该如何通信?这里就讲用props的方式。

  组件有state和props两种状态值,state是内部值,props是外部传进来的值。

//引用Home组件
render() {
    return <div>
        <Home text="byebye world"></Home>
    </div>;
}

class Home extends React.Component {
    constructor(props) {
        super(props);
        //定义数据
        this.state = {
            text: this.props.text
        };
    }

    render() {
        return <div>
            {this.state.text}
        </div>;
    }
}

  在引用Home组件时,在Home标签上带上属性来传值,在Home组件内的构造函数接收到this上。

  父组件通过props将值传给子组件。而子组件想将值传给父组件,则需要父组件通过props将自己的函数传给子组件,由子组件调用父组件的函数。

//父组件
class
App extends React.Component { constructor() { super(); //定义数据 this.state = { text: "hello world", count: 0 }; } handleClick(count) { this.setState({ count: count }); } render() { return <div> 父组件:{this.state.count} <Home text="byebye world" click={this.handleClick.bind(this)} count={this.state.count}></Home> </div>; } }
//子组件
class Home extends React.Component { constructor(props) { super(props); //定义数据 this.state = { text: this.props.text, count: this.props.count }; } handleClick(e) { var count = this.state.count + 1; this.setState({count:count}); this.props.click(count); //注意这种写法会有延迟,因为setState方法在这里是异步的,count值还是0。或者改用setState的回调方法 // this.setState({ // count: this.state.count + 1 // }); // this.props.click(this.state.count); } render() { return <div> {this.state.text} 子组件:{this.state.count} <input type="button" onClick={this.handleClick.bind(this)} /> </div>; } }

  这里实现了修改子组件数值,然后将子组件得数值传给父组件输出。

 

posted @ 2021-10-08 11:22  shine声  阅读(101)  评论(0编辑  收藏  举报