代码之家  ›  专栏  ›  技术社区  ›  Ciprian

React现有应用程序中的组件

  •  0
  • Ciprian  · 技术社区  · 7 年前

    '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 是因为它们将显示来自该对象的数据。

    1 回复  |  直到 7 年前
        1
  •  1
  •   weibenfalk    7 年前

    您可以创建另一个组件并在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
    }
    

    然后将其作为组件导入课程表单组件:

    import AnotherComponent from '.. your filepath here';
    

    并在CourseForm的渲染方法中使用其他组件:

    <另一个组件sendObject={this.state.someObject}/>