美文网首页
react练习

react练习

作者: dxcqcv | 来源:发表于2018-01-02 07:51 被阅读0次

    1. 带有自己名字的HelloMessage组件,名字通过props传递。

    import React from 'react'
    import ReactDOM from 'react-dom'
    
    function ShowMsg({name}) {
      return (
        <h1>Hello, {name}</h1>
      )
    }
    
    const Hello = React.createClass({
      getInitialState() {
        return {
          msg: 'Long'
        }
      },
      handleInput(e) {
        this.setState({msg: e.target.value})
      },
      render() {
        return (
          <div>
            <input
               value={this.state.msg}
               onChange={this.handleInput} />
            <ShowMsg name={this.state.msg} />
          </div>
        ) 
      } 
    })
    
    ReactDOM.render(
      <Hello/>,
      document.getElementById('container')
    )
    

    2. 一个背景色为绿色的盒子,3秒后颜色变为红色。

    index.css

    * {
        margin: 0; padding:0;
    }
    
    .box {
        width: 200px; height:200px; 
        margin: -100px -100px; position: fixed; top: 50%; left: 50%;
    }
    

    index.js

    import React from 'react'
    import ReactDOM from 'react-dom'
    import './index.css'
    
    class Box extends React.Component {
    
        constructor(props) {
            super(props)
            this.state = {c: 'green'}
            this.change = this.change.bind(this)
        }
    
        componentDidMount() {
            setTimeout(
                () => this.change(),
                3000
                )
        }
    
        change() {
            this.setState({
                c: 'red'
            })
        }
    
        render() {
            return (
                <div className="box" style={this.state.c === 'green' ? {background:'green'} : {background:'red'}}></div>
                )
        }
    }
    
    ReactDOM.render(
        <Box />,
        document.getElementById('root')
    )
    

    相关文章

      网友评论

          本文标题:react练习

          本文链接:https://www.haomeiwen.com/subject/dztfnxtx.html