React 组件之间的传值

2019-06-20  本文已影响0人  蕉下客_661a
import React from 'react'

// 父组件
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      arr:['lily','lina']
    };
  };
  handleAddFn(inew){
    const {arr} = this.state;
    this.setState({
      arr:[inew,...arr]
    })
  }
  render() {
    const { arr } = this.state;
    return(
      <div>
        <ContentInput add={this.handleAddFn.bind(this)}/>
        <ContentList arr={arr}/>        
      </div>
    )
  }
}
class ContentInput extends React.Component {
  state={
    value:''
  }
  handleChange(e){
    this.setState({
      value:e.target.value
    })
  }
  handleKeyDown(e){
    if(e.keyCode ==13){
      this.props.add(e.target.value)
      this.setState({
        value:''
      })
    }    
  }
  render() {
    return(
      <input type="text" placeholder="输入新人员" value={this.state.value} onKeyDown={this.handleKeyDown.bind(this)}  onChange={this.handleChange.bind(this)}/>      
    )
  }
}
class ContentList extends React.Component {  
  render() {
    return(
      <ul>{
        this.props.arr.map((item,index)=>{
          return <li key={index}>{item}</li>
        })
      }</ul>
    )
  }
}
export default App 
上一篇下一篇

猜你喜欢

热点阅读