在反应中从父级调用子组件方法 [英] Call child component method from parent in react

查看:41
本文介绍了在反应中从父级调用子组件方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

第一个是父级,第二个是子级

class TodoComp extends React.Component {构造函数(道具){超级(道具);this.handleKeyPress = this.handleKeyPress.bind(this);}componentDidMpunt(){console.log(this._child.someMethod());}handleKeyPress(事件){if(event.key === '回车'){var t = event.target.value;}}使成为(){返回 (<div><输入className="inputTodo"类型=文本"placeholder="想成为英雄……!"onKeyPress={this.handleKeyPress}/><列表/>

);}}导出默认类 List extends React.Component {构造函数(){极好的();this.flipDone = this.flipDone.bind(this);this.state = {todos: Array(3).fill({ content: '', done: false})};}翻转完成(ID){让索引 = Number(id);this.setState({待办事项: [...this.state.todos.slice(0, index),Object.assign({}, this.state.todos[index], {done: !this.state.todos[index].done}),...this.state.todos.slice(index + 1)]});}使成为() {const myList = this.state.todos.map((todo, index) => {返回 (<待办事项键={索引}clickHandler={this.flipDone}id={索引}待办事项={待办事项}handleText={this.handleText}/>);})返回 (<ul className="list">{我的列表});}ReactDOM.render(,document.getElementById('myList'));

解决方案

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

从父级渲染列表组件

然后以 this.refs.myList.handleNewText()

的形式访问 handleNewText() 函数

更新:

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

this.myList=ref}/>

然后像访问子函数

this.myList.handleNewText()

I have simple component called List which is a simple ul with some li inside. Each li is a simple component. I have other parent component which render one input field and the List component. Tapping on Send key I catch text of input field. I want to call for example a function called handleNewText(inputText) but this function need to stay inside List component because the state I use to populate other li components live in List component.

I don' t want to refactor List and MyParent component passing the manage of data from List to MyParent.

first is parent and second is child

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'));

解决方案

You need to make use of refs to call a function in the child component from the parent component

render the List component from parent as

<List ref="myList"/>

and then access the handleNewText() function as this.refs.myList.handleNewText()

UPDATE:

Strings refs are no longer recommended by React, you should rather use ref callbacks, check this

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

and then access the child function like

this.myList.handleNewText()

这篇关于在反应中从父级调用子组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆