繁体   English   中英

在现有应用程序中反应组件

[英]React components in existing application

我开始将React组件添加到现有网站。 我目前有一个看起来像这样的简单组件。

'use strict';

const element = React.createElement

class CourseForm extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      someObject: ''
    }
  }

  changeObject() {
    //this value will change on various events
    this.setState({ someObject: {key: value} })
  }

  render() {
    return (
      <div>

        This is a react form!

      </div>
    )
  }
}

const domContainer = document.querySelector('#react-course-form')
ReactDOM.render(element(CourseForm), domContainer)

html元素用于显示组件。

<div id="react-course-form"></div>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

  <!-- Load React component. -->
  <script type="text/babel" src="./js/components/CourseTabs.jsx"></script>
  <script type="text/babel" src="./js/components/CourseForm.jsx"></script>

我想做的是包含另一个组件,并向该组件发送有关事件的数据。

render() {
    return (
  <div>

    This is a react form!
    <button onClick={this.changeObject}>change</button>

    <div id="another-component" sendObject="this.state.someObject">
    <div id="another-component2" sendObject="this.state.someObject">

  </div>
)
}

因此,我基本上希望子组件知道someObject是什么,因为它们将显示该对象的数据。

您可以创建另一个组件,然后导入CourseForm组件。 然后,您可以像在示例中一样在渲染方法中使用它并发送道具。 您现在仍未使用常规div,因此无法正常工作。

例:

<AnotherComponent sendObject={this.state.someObject} />

当您的CourseForm组件中的状态更新时,子组件将自动重新呈现新数据,并将其作为道具。

首先创建您的新组件:

class AnotherComponent extends Component {
  // Your code goes in here. You can access the object data you send 
  // in by props by grabbing it from this.props.someObject
}

然后将其作为组件导入到CourseForm组件中:

import AnotherComponent from '.. your filepath here';

并在CourseForm的渲染方法中使用AnotherComponent:

<AnotherComponent sendObject={this.state.someObject} />

暂无
暂无

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

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