【问题标题】:How react know when i sent props to component when i not accepting arguments on constructor当我不接受构造函数的参数时,如何反应知道我何时向组件发送道具
【发布时间】:2021-03-07 17:42:34
【问题描述】:

React 是如何知道 props 的,我正在向组件发送 props,我不接受构造函数的参数,而是通过 render() 方法访问 props。

import ReactDOM from 'react-dom';
import './index.css';

import App from './App';

import reportWebVitals from './reportWebVitals';
ReactDOM.render(
  <React.StrictMode>
    <App myApp={'myApp'}/>
  </React.StrictMode>,
  document.getElementById('root')
);
// this is app component
import React, {Component} from 'react';
class App extends Component {
  constructor() {
    super()
    this.state = {};
    console.log(this.props.myApp) // undefined
  }
  render() {
    console.log(this.props.myApp) // 'myApp' how and why, i'm not accepting arguments in contrutor why and how render method know this.props.myApp
  }
}
exports default App;
// this is my assumption what react doing
const obj = new App(props);

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你需要重建你的构造函数:

    constructor(props) {
      super(props);
      console.log(this.props.myApp); // 'myApp'
    }
    

    更多信息在这里: What does calling super() in a React constructor do?

    【讨论】:

    • 我想知道当我不接受构造函数中的参数时,render() 方法如何访问道具
    • 可以在此处找到类似的讨论:stackoverflow.com/questions/30571875/… "React 在调用构造函数后立即从外部设置实例上的 .props。"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多