[英]How to embed components in one another in reactjs?
如何将另一个组件导入该组件? 我是否需要制作另一个文件并在那里声明类? 如果是这样,我如何将其导入该方案? 我正在使用babel
和webpack
。
具体来说,我希望输入是它自己的组件,并具有传递给MyReactApplication
组件的自己的状态。 我只需要隔离输入逻辑,因为它将在应用程序的许多地方使用。
var React = require('react');
var ReactDOM = require('react-dom');
class MyReactApplication extends React.Component {
constructor(props){
super(props);
this.state = {
color: "hotpink"
};
}
componentDidMount() {
this.setState({
color: "steelblue"
});
}
changeColor(event) {
this.setState({
color: event.target.value
});
}
render() {
const styleObj = {
backgroundColor: this.state.color
};
return(
<section className="temp" style={styleObj} id="my-user">
<h1>{this.state.color}</h1>
<input value={this.state.color} onChange={this.changeColor.bind(this)} />
</section>
);
}
}
ReactDOM.render(<MyReactApplication name="Mustafa"/>, document.getElementById("app"));
您必须导入它: import Component from './file'
或var Component = require('./file');
import Component from './file'
var Component = require('./file');
然后,您可能需要将其用于渲染<Component />
您应该真正了解一下React的基础知识。 https://facebook.github.io/react/tutorial/tutorial.html
一号档案:
import React from 'react';
export default class Textbox extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<span>my text box</span>
)
}
}
第二个文件将使用Textbox:
import React from 'react';
import Textbox from './textbox';
export default class Textbox extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="texbox-wrapper">
<Textbox />
</div>
)
}
}
babel
将转换文件,而webpack
将看到依赖关系并将文件捆绑在一起(使用正确的配置)。
您需要从试图隔离并导出它的输入文件中制作一个新组件。 然后, import InputComponentName from 'file_path'
(es6)或require('file_path')
(es5) import InputComponentName from 'file_path'
并像<InputComponentName />
一样使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.