【问题标题】:Call child component method from parent in react在反应中从父级调用子组件方法
【发布时间】:2016-10-25 08:48:06
【问题描述】:

我有一个名为 List 的简单组件,它是一个简单的 ul,里面有一些 li。每个 li 都是一个简单的组件。 我有其他父组件呈现一个输入字段和 List 组件。点击 Send 键我捕捉到输入字段的文本。例如,我想调用一个名为 handleNewText(inputText) 的函数,但该函数需要保留在 List 组件中,因为我用来填充其他 li 组件的状态位于 >列表组件。

我不想重构 ListMyParent 组件,将数据管理从 List 传递到 MyParent

第一个是父母,第二个是孩子

class TodoComp extends React.Component {
  constructor(props){
    super(props);
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }

  componentDidMpunt(){
    console.log(this._child.someMethod());
  }


  handleKeyPress(event){
    if(event.key === 'Enter'){
      var t = event.target.value;

    }
  }

  render(){
    return (
        <div>
          <input
            className="inputTodo"
            type="text"
            placeholder="want to be an hero...!"
            onKeyPress={this.handleKeyPress}
          />
          <List/>
        </div>
    );
  }

}


export default class List extends React.Component {
  constructor() {
    super();
    this.flipDone = this.flipDone.bind(this);
    this.state = {
      todos: Array(3).fill({ content: '', done: false})
    };
  }

  flipDone(id) {
    let index = Number(id);

    this.setState({
      todos: [
        ...this.state.todos.slice(0, index),
        Object.assign({}, this.state.todos[index], {done: !this.state.todos[index].done}),
        ...this.state.todos.slice(index + 1)
      ]
    });
  }

  render() {

    const myList = this.state.todos.map((todo, index) => {
      return (
        <Todo key={index}
              clickHandler={this.flipDone}
              id={index}
              todo={todo}
              handleText={this.handleText}
        />
      );
    })

    return (
      <ul className="list">
        {myList}
      </ul>
    );
  }


ReactDOM.render(<TodoComp />,document.getElementById('myList'));

【问题讨论】:

标签: reactjs


【解决方案1】:

你需要利用refs从父组件调用子组件中的函数

将 List 组件从父组件渲染为

<List ref="myList"/>

然后以this.refs.myList.handleNewText() 的身份访问handleNewText() 函数

更新:

React 不再推荐字符串引用,你应该使用引用回调,检查this

<List ref={(ref) => this.myList=ref}/>

然后像访问子函数

this.myList.handleNewText()

【讨论】:

    【解决方案2】:

    添加到@shubham-khatri 解决方案:

    如果您引用的是 已连接 子组件...

    一个。那个孩子必须在(4th)配置参数中说withRef: true

    @connect(store => ({
        foo: store.whatever
        …
    }),null,null,{ withRef: true })
    

    b.通过getWrappedInstance()访问(注意getWrappedInstance也需要叫()

    getWrappedInstance().howdyPartner()
    

    【讨论】:

      【解决方案3】:

      当功能组件出现时,我开始学习 React。我尝试成功的另一种方法是返回您希望在 JSON 中作为闭包访问的函数。我喜欢这种方法,因为闭包是 Javascript 的一种构造,即使 React 再次更新,它也应该仍然有效。下面是一个子组件的例子

      function Child(){
          //declare your states and use effects
          const [ppp, setPPP] = useState([]);
          const [qqq, setQQQ] = useState(2);
          //declare function that you want to access
          function funcA(){ /*function to interact with your child components*/}
          function funcB(){ /*function to interact with your child components*/}
      
          //pure React functional components here
          function Content(){
               //function that you cannot access
               funcC(){ /*.....*/}
               funcD(){/*.......*/}
               //what to render
               return (
                 <div> 
                     {/* your contents here */} 
                 </div>
               )
          }
          //return accessible contents and functions in a JSON
          return {
              content: Content, //function for rendering content
              ExposeA: funcA,   //return as a closure
              ExposeB: funcB,   //return as a closure
          }
      }
      

      以下是如何在父级中呈现子级内容的示例

      function Parent(){
          let chi = Child();
          let ChildContent = chi.Content;
          //calling your exposed functions
          //these function can interacts with the states that affects child components
          chi.ExposeA();  
          chi.ExposeB();
          //render your child component
          return (<div>
              <div> {/* parent stuff here */</div>
              <div> {/* parent stuff here */</div>
              <ChildContent {/*Define your props here */} />
          </div>)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-17
        • 1970-01-01
        • 2015-07-28
        • 1970-01-01
        • 2021-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多