简体   繁体   English

如何在其他组件上调用组件函数,但是从其他组件调用? 应对

[英]How to call a component function on other component, but from the other component ? React

Currentl, I am doing a React project. Currentl,我正在做一个React项目。 I want to ask: lets say there are 3 components, A,B, and C. A is my container, B is the input one, and C is the output one. 我想问一下:假设有3个组件,A,B和C. A是我的容器,B是输入组件,C是输出组件。

this is my component A : 这是我的组件A:

import React, { Component } from 'react';
import './App.css';
import {SubmitComponent} from './submitComponent.js'
// import {OutputCo} from './TopicsContainer.js'

const containerStyle = {
  border: '2px solid black',
  width: '70%',
  height: 'auto',
  marginLeft: 'auto',
  marginRight: 'auto',
  marginBottom: '100px',
};

class App extends Component {
  render() {
    return (
      <div style={containerStyle}>
        <h1 style={{textAlign:'center'}}>Coding Exercise</h1>
        <hr />
        <SubmitComponent />
        <OutputComponent />

      </div>
    );
  }
}

export default App

Component B is SubmitComponent, component C is OutputComponent, my B is taking the input and save it as its state : import React, { Component } from 'react'; 组件B是SubmitComponent,组件C是OutputComponent,我的B正在获取输入并将其保存为其状态:import React,{Component} from'reaction';

import React, { Component } from 'react';
const createstyleouter ={
    border : '2px solid #AAA',
    width : '98%',
    height: 'auto',
    marginLeft: 'auto',
    marginRight: 'auto',
    marginTop:'35px',
    marginBottom:'50px',
};

const createstyleinner ={
    // border: '2px solid blue',
    marginLeft: 'auto',
    marginRight: 'auto',
    marginTop: '10px',
    width: '98%',

}

export class SubmitComponent extends Component {


    constructor(props) {
        super(props);
        this.state = {
            title: '',
            desc: ''
        }
        this.newTitle = this.newTitle.bind(this);
        this.newDesc = this.newDesc.bind(this);
    }

    newTitle(e) {
        this.setState({
            title: e.target.value
        });
    }

    newDesc(e) {
        this.setState({
            desc: e.target.value
        });
    }

    render() {
        return (
            <div style={createstyleouter}>
                <div style={createstyleinner}>
                    <p><strong>Title:</strong></p>
                    <textarea style={{width:'100%', height:'20', fontSize:'17px'}} onChange={this.newTitle} maxLength='150' value={this.state.title} placeholder="Enter your topic's title"></textarea>
                    <p>Description:</p>
                    <textarea style={{width:'100%', height:'70', fontSize:'17px'}} onChange={this.newDesc} maxLength='150' value={this.state.desc} placeholder="Enter your topic's description'"></textarea>
                    <button style={{padding: '10px', marginBottom:'10px'}}>Submit</button>
                </div>
            </div>
        );
    }
}

I literally did not have any idea how to send this state to C so C can post is as the topic, Please help 我字面上根本不知道如何将此状态发送给C所以C可以发布作为主题,请帮忙

If you wish to call method from other components, you have to pass method around as props . 如果你想从其他组件调用方法,你必须将方法作为props传递。

class Parent extends Component {
  render() {
    return (
      // pass method as props to Child component
      <Child parentMethod={this.parentMethod}/>
    );
  }

  parentMethod() {
    console.log('Hello World');
  }
}

class Child extends Component {
  render() {
    return (
      <button onClick={this.handleClick}>Fire parent method</button>
    );
  }

  handleClick() {
    // parent method passed to child is now available as props
    // you can call it now & even pass arguments if you like
    this.props.parentMethod('foo', 'bar', 2, ['foo', 'bar'], {foo: 'bar'});
  }
}

If passing around methods gets tricky (eg one component wants to call a method of component that is in a totally different place in your component tree), you could consider context . 如果传递方法变得棘手(例如,一个组件想要调用组件树中完全不同位置的组件方法),则可以考虑上下文

But be warned - read the docs I linked, it makes your code harder to understand and get into. 但要注意 - 阅读我链接的文档,它会使您的代码更难理解和进入。

您需要提升状态,以便状态作为从容器到子组件的道具传递。

Let us say you have a structure 我们假设你有一个结构

class A
{
getResponse:function(res)
{
set you state//
this.setState({
state:res
})

}
<B state={this.state} callback={this.getResponse}/>
<C state={this.state}  />//state is the updated state by function callback

}

in Component B you need to call function callback as 在组件B中,您需要将函数回调调用为

class B
{
callAComponent:function(res)
{
this.props.callback(res)

}
render{

return(

<input type="text" onChange={this.callAComponent}//whaever event you are performing
)

}
}

Now send the update state in C component 现在在C组件中发送更新状态

In the constructor of the parent: 在父级的构造函数中:

this.childElement = React.createRef();

In your child element in the parent: 在父级的子元素中:

<Child ref = {this.childElement}>

To call a method of the child use: 要调用孩子使用的方法:

this.childElement.current.aFunctionInChildClass();

For more information in react documentation/refs and the dom 有关反应文档/参考和dom的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM