【问题标题】:Reactjs pass props based on loaded componentReactjs 根据加载的组件传递 props
【发布时间】:2017-01-06 04:55:46
【问题描述】:

我需要关于如何在加载时将 Reactjs 道具从组件传递到我的应用程序的建议。当我的道具在 app.js 中时,我可以传递值,但是从单独的组件加载时如何处理道具?

以下是 app.js 中到目前为止的工作:

import React, { PropTypes, Component } from 'react';
import { Grid, Nav, Navbar, NavItem, Jumbotron } from 'react-bootstrap';
import { Link } from 'react-router';
import { LinkContainer, IndexLinkContainer } from 'react-router-bootstrap';

function HeaderTitle(props) {
  return <h1>{props.name}</h1>;
}

const headerTitle = <HeaderTitle name="About Page" />;

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

<p>{headerTitle.props.name}</p>

【问题讨论】:

  • 你的意思是从 App 传递 props 到 HeaderTitle 吗?
  • 我希望在使用 react-router 加载每个组件时传递 prop。
  • 好的,所以孩子对父母?请在下面查看我的答案 - 第 2 部分
  • 但是把道具传到哪里去了?
  • 我想将 /views 中组件的标题道具传递给父 app.js 中的 div。

标签: javascript reactjs


【解决方案1】:

父母对孩子

如果你想通过所有的道具:

render() {
  return (
    <div>
      <HeaderTitle {...this.props} />     
    </div>
  );
}

或者如果只是一些:

render() {
  return (
    <div>
      <HeaderTitle name={this.props.name} />     
    </div>
  );
}

孩子到父母

如果你的意思反过来,你需要使用回调

// app
render() {
  return (
    <div>
      <HeaderTitle onGetName={(name) => this.setState({childName: name})} />     
      <p>{this.state.childName}</p>
    </div>
  );
}

// headertitle
componentDidMount() {
  // maybe some async call or something
  axios
    .get('/api/say-my-name')
    .then(response => this.props.onGetName(response.data);
}

【讨论】:

    【解决方案2】:

    所以我猜你需要一些东西,比如将组件从一个文件导入另一个文件。因此,您可以选择从另一个文件导入和导出组件,因为 React 组件基本上是对象。如果你有类似的东西,在 index.js 中

    const headerTitle = <HeaderTitle name="About Page" />;
    
    export default headerTitle;
    

    在 app.js 中

    import React, { PropTypes, Component } from 'react';
    import { Grid, Nav, Navbar, NavItem, Jumbotron } from 'react-bootstrap';
    import { Link } from 'react-router';
    import { LinkContainer, IndexLinkContainer } from 'react-router-bootstrap';
    import HeaderTitle from '/// put the file relative location to app.js"
    
    function HeaderTitle(props) {
      return <h1>{props.name}</h1>;
    }
    
    class App extends React.Component {
      constructor(props) {
        super(props);
      }
      render() { ...
    
    <p>{headerTitle.props.name}</p>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      • 2020-09-15
      • 2018-03-22
      • 2019-11-18
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多