我开始将React组件添加到现有网站。我目前有一个看起来像这样的简单组件。
public static String reverseWords(String str) {
StringBuilder buf = new StringBuilder(str.length());
String[] words = str.trim().split("\\s+");
for (int i = words.length - 1; i >= 0; i--) {
if (buf.length() > 0)
buf.append(' ');
buf.append(words[i]);
}
return buf.toString();
}
使用html元素显示组件。
'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)
我想做的是包含另一个组件,并将有关该组件事件的数据发送给它。
<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>
)
}
是什么,因为它们将显示该对象中的数据。
答案 0 :(得分:1)
您可以创建另一个组件,然后将其导入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} />