简体   繁体   English

如何从父组件中的子组件呈现功能的jsx

[英]how to render jsx of function from child component in parent component

I am having a child component a parent component. 我有一个子组件,一个父组件。 I am having a function in child component which returns some jsx what i want to do is use that function to return the same jsx in parent component but iam unable to figure out a way to do that. 我在子组件中有一个函数,该函数返回一些jsx,我想做的是使用该函数在父组件中返回相同的jsx,但是我无法找到一种方法来做到这一点。 I am giving my minimal code: 我给我最小的代码:

parent component: 父组件:

    class App extends Component {
  render() {
    return (
      <div className="App">
        <Player ref={instance=>{this.player = instance}} />
        {this.player.func('aaa.com','bbb')}
      </div>
    );
  }
}
  export default App;

Child component: 子组件:

    import React, { Component } from "react";

class Player extends Component {
  func = (url, label) => {
        return (
            <button onClick={() => this.func(url)}>
                {label}
            </button>
        )
    }
  render() {
    return <div>1</div>;
  }
}
export default Player;

Error: Cannot read property 'func' of undefined 错误:无法读取未定义的属性“ func”

// //

Note: i know i can use the jsx in parent component by copy-pasting but iam trying to figure out a way of doing like this. 注意:我知道我可以通过粘贴粘贴在父组件中使用jsx,但是我试图找出一种这样做的方法。 I am having doubt that is it even possible 我怀疑是否有可能

您可以创建一个Player对象并使用该对象访问函数。

new Player().func('aaa.com','bbb')

I don't quite understand what you need exactly but I think that you're looking to pass some jsx element from the Child component to the parent component. 我不太了解您到底需要什么,但我认为您正在寻求将一些jsx元素从Child组件传递到父组件。 What we can do is declare a propType callback on the child component and then implement it on the parent component like so. 我们可以做的是在子组件上声明propType回调,然后像这样在父组件上实现它。

import React from 'react';

class Hello extends React.Component {
  constructor() {
    super();
    this.state = {
      // this state will keep the element returned by the parent
      returnElements: null
    }
    this.onReturn = this.onReturn.bind(this);
  }

  // this method will be fired when the Child component returns callback for onSomethingReturned
  onReturn(element) {
    this.setState({
      returnElements: element
    })
  }
  render () {
    return (
      <div>
        <h1>Hello, React!</h1>
        <Child onSomethingReturned={this.onReturn} />
        {/* I am going to display the state here */}
        {this.state.returnElements}
      </div>
    )
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const element = <h3>this is child element</h3>;
    // will call the propType callback function with a element I want to return
    this.props.onSomethingReturned(element);
  }

  render() {
    return (null);
  }
}


export default Hello;

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

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