鍍金池/ 問答/HTML/ react 中,父組件如何調(diào)用子組件的方法,或者有沒有可能設(shè)置子組件的state

react 中,父組件如何調(diào)用子組件的方法,或者有沒有可能設(shè)置子組件的state(不用redux)

如題想請教一下大家,react中,父組件有沒有辦法調(diào)用子組件的方法,或者設(shè)置子組件的state。謝謝!

回答
編輯回答
夏夕

當(dāng)然可以啦====我們需要使用props來傳遞啊---redux 產(chǎn)生的根本就在于狀態(tài)控制太多,不易管理,才用redux嘛。。而且一般情況下,也不推薦用redux。能用用react本身的狀態(tài)做的,盡量本身來控制。就是一個項目里面你如果倔強(qiáng),是完全可以不用redux來幫你管理復(fù)雜狀態(tài)的---請看一下redux的三大原則吧--
一般情況 這樣控制字組件的狀態(tài)

中午看了一下這片文章,推薦給你

<Recommend 
                selected_tag={this.state.selectTags}
                screeningItems={this.state.screeningItems}
              /> 
               <RecommendLi
          key={index}
          tagData={item}
          resetHangye={this.resetHangye.bind(this)}
          selectedTag={this.props.selected_tag[item.name] || []}
          selectCallback={this.selectCallback}
        />
        
        <div className={Style.licenter}>
        <div className={Style.title}>{this.props.tagData.title}</div>
        <ul className={Style.ul}>
          {
            this.props.tagData.values.map((item, index)=>{
              return  (
                <li 
                  key={index}
                  className={this.state.selectTag.indexOf(index) > -1 ? Style.active : Style.li}
                  onClick={()=>this.handleClick(item, index)}
                >{item.tagName}</li>
              )
            })
          }
        </ul>
      </div>  
2018年9月6日 08:11
編輯回答
冷眸

父組件為子組件設(shè)置 refs, 可以獲取到子組件對象, 也就可以調(diào)用子組件的內(nèi)部方法.

// Child
class Child extends Component {
    childFunction() {}
}

class Parent extends Component {
    // 調(diào)用
    parentFunction() {
        this.child.childFunction();
    }

    render() {
        return (
            <Child ref={(child) => { this.child = child; }} />
        );
    }
}
2017年5月12日 19:08
編輯回答
汐顏

父組件調(diào)用子組件的方法,一般使用refs,子組件調(diào)用父組件一般采用callback.
下面的例子是父組件調(diào)用子組件的方法:

class Parent extends React.Component {
    render() {
        return(
            <div>
                <Child ref={r => this.child = r}/>
            </div>
        );
    }
    
    myFunction() {
        this.child.childFunction();
    }
}

class Child extends React.Component {
    render() {
        //....
    }
    
    childFunction() {
    
    }
}

注意的是,stateless寫法中沒有refs.

2017年4月6日 23:27