如何从子组件访问父道具?

时间:2021-03-14 16:37:22

标签: reactjs react-props

如何在Child的标签和函数sayhello中访问Parent的props?
(我可以访问兄弟姐妹和孩子而不传递道具作为参数,但不能访问父母)
____________________________________________

并且(远离这个例子)
如果<?php echo get_site_url();?>指的是this,如何访问Child的props?
如果 Parent 将 Child 引用为 html 标记,是否有将结果转换为 react 组件类的函数? (不将此作为类重新分配给新变量 this 而不是 () =>
孩子:

function()

家长:

class Child extends Parent{
   constructor(props){
       super(props);
   }
   render() {
       return (
          <p>{Parent.props.hello}</p>     // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
          <button onClick={sayhello.bind(this)}></button> // <<<<<<<<<<<<<<<<<<<<<<<<
       ); 
   }
}

说你好:

class Parent extends React.Component{
   constructor(props){
       super(props);
   }
   render() {
      <>
          <Child/>
      </>
   }
}

1 个答案:

答案 0 :(得分:0)

如果你bind组件中的函数,可以参考this.props


class Child extends React.Component {
  render() {
    return (
      <>
        <button onClick={sayhello.bind(this)}>Click</button>
      </>
    );
  }
}

class Parent extends React.Component {
  render() {
    return (
      <>
        <Child someProp="hello" />
      </>
    );
  }
}

function sayhello() {
  console.log(this.props);
}

Edit React Template (forked)