实际上我的代码非常复杂,但为了简单起见,我举了这个例子:
我有两个组成部分:
Component_A:
import React, {PropTypes} from 'react';
class Component_A extends React.Component {
constructor(props, context){
super(props, context);
}
render(){
return (
<div>Component A</div>
);
}
}
export default Component_A;
Component_B:
import React, {PropTypes} from 'react';
class Component_B extends React.Component {
constructor(props, context){
super(props, context);
}
render(){
return (
<div></div>
);
}
}
export default Component_B;
应用程序文件:
import React, {PropTypes} from 'react';
import Component_B from './Component_B';
class App extends React.Component {
render() {
return (
<div>
<Component_A />
<Component_B />
</div>
);
}
}
export default App;
索引文件:
import React from 'react';
import { render } from 'react-dom';
import App from './App';
render(
<App />,
document.getElementById('app')
);
现在在页面渲染后,我将从服务器接到电话,那时我想将 Component_A附加到Component_B中。对此有什么解决方案吗?
你们中的大多数人都可以看到这种荒谬,并建议用国家反应机构来做这件事。但正如我上面所写,这是一个非常复杂的项目。所以如果我们可以通过追加来实现它,那将非常容易。
答案 0 :(得分:0)
解决方案完全取决于项目的架构。您可以在任何时候有条件地渲染组件。如果我理解你,你可以这样做:
//Component_A:
import React, {PropTypes} from 'react';
class Component_A extends React.Component {
render(){
return (
<div>Component A</div>
);
}
}
export default Component_A;
//Component_B:
import React, {PropTypes} from 'react';
class Component_B extends React.Component {
render(){
return (
<div>{this.props.children}</div>
);
}
}
export default Component_B;
//app
import React, {PropTypes} from 'react';
import Component_A from './Component_A';
import Component_B from './Component_B';
class App extends React.Component {
componentWillMount() {
api.fetchData().then(data => {
this.setState({data});
})
}
render() {
return (
<div>
<Component_B/>
{this.state.data && <Component_A />}
</Component_B>
</div>
);
}
}
export default App;
或者您可以将Component_A
移至Component_B
:
//Component_A:
import React, {PropTypes} from 'react';
class Component_A extends React.Component {
render(){
return (
<div>Component A</div>
);
}
}
export default Component_A;
//Component_B:
import React, {PropTypes} from 'react';
import Component_A from './Component_A';
class Component_B extends React.Component {
render(){
if (!this.props.data) {
return (
<div>Loading...</div>
);
}
return (
<div>
<Component_B />
</div>
);
}
}
export default Component_B;
//app
import React, {PropTypes} from 'react';
import Component_B from './Component_B';
class App extends React.Component {
componentWillMount() {
api.fetchData().then(data => {
this.setState({data});
})
}
render() {
return (
<div>
<Component_B data={this.state.data} />
</div>
);
}
}
export default App;
您始终可以从组件返回null
以隐藏其html
class Component_A extends React.Component {
render(){
if (!this.props.visible) return null;
return (
<div>Component A</div>
);
}
}