美文网首页
react的ref属性使用:

react的ref属性使用:

作者: 五四青年_4e7d | 来源:发表于2020-02-18 21:24 被阅读0次
    //父页面:
    import React, { Component, Fragment } from 'react';
    import Home from  './App.test'
    import './App.css';
    
    class App extends Component {
      constructor(props) {
        super(props)
        this.state = {
          inputValue: '',
          list: ['js' ,'css']
        }
      }
      render() {
        return (
          
          <Fragment>
           <div>
             <label>增加服务</label>
             <input  value={this.state.inputValue}  onChange={this.inputChange.bind(this)}  ref={(input) => {this.input = input}}/>
             <button onClick={this.addLsit.bind(this)}>增加</button>
           </div>
           <ul  ref={(ul) => {this.ul = ul }}>
             {
               this.state.list.map((item,index)=>{
                 return (
                     <Home
                      key={index+item} 
                      content={item}  
                      index={index}
                      deleteItem={this.deleteItem.bind(this)} />
                 )
               })
             }
           </ul>
            </Fragment>
        )
      }
      inputChange(e){
        this.setState({
          inputValue:this.input.value
        })
       
      }
      //增加列表:
      addLsit(){
        this.setState({
          list:[...this.state.list,this.state.inputValue],
          inputValue:''
        },()=>{
          console.log(this.ul.querySelectorAll('li').length)
        })
      }
    
      //删除列表项:
      deleteItem(index){
        let list = this.state.list
        list.splice(index,1)
        this.setState({
          list:list
        })
    
      }
    }
    export default App;
    
    
    //子页面:
    import React, { Component, Fragment } from 'react';
    
    import PropTypes from 'prop-types'
    
    class Home  extends Component {
      constructor(props){
       super(props)
       this.hadleClick = this.hadleClick.bind(this)
       }
      
      render() {
        return (
          <li onClick={this.hadleClick}>{this.props.avname}{this.props.content}</li>
        )
      }
    
     hadleClick(){
       console.log(this.props.index)
       this.props.deleteItem(this.props.index)
     }
    }
    
    Home.propTypes={
      avname:PropTypes.string.isRequired,
      content:PropTypes.string,
      index:PropTypes.number,
      deleteItem:PropTypes.func
    }
    
    Home.defaultProps={
      avname: '项目'
    }
    
    
    
    export default  Home;
    
    

    相关文章

      网友评论

          本文标题:react的ref属性使用:

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