React点击谁谁显示

实现效果如下:

React点击谁谁显示_第1张图片

首先 app.js 组件代码

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

import Btn  from './button'

class App extends Component {
    constructor(props){
        super(props)
        this.state={
            display:false
        }
    }
  render() {
    return (
      
"App" onClick={()=>{ this.setState({ display:false }) }}> this.state.display}/> this.state.display}/> this.state.display}/> this.state.display}/>
); } } ReactDOM.render( , document.getElementById('container') );

其次是 button.js 组件代码

import React, { Component } from 'react';


class button extends Component {
    constructor(props){
        super(props)
        this.state={
             display: this.props.display
        }
    }

    componentWillReceiveProps(nextProps){
        if(this.state.display){
            this.setState({
              display: nextProps.display
            })
        }
    }

    render() {
        return (
            <div style={{height:100,width:'100%',margin:10,border:'1px solid #000'}}>
               
                <div style={{backgroundColor:'red',width:50,height:50,display:this.state.display?'block':'none'}}>
                div>
            div>
        );
    }
}

export default button;

核心就是是componentWillReceiveProps() 函数的用法

你可能感兴趣的:(ReactNative,react,javascript,前端开发)