[英]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.