我有一个ReactJS组件库,如下代码:
components.js
class Comp1 extends Component {
render () {
return (
<div>Component 1 Text: {this.props.text}</div>
);
}
}
class Comp2 extends Component {
render () {
return (
<div>Component 2 Text: {this.props.text}</div>
);
}
}
export components = {
Comp1,
Comp2
}
主要组件需要根据传递的属性选择第一个呈现:
main.js
import { components } from './components';
class Main extends Component {
getComponent = (name) => {
return components[name];
};
render () {
let comp = this.getComponent(this.props.componentName);
return (
<div>
<comp <=== HOW TO CALL THE GIVEN COMPONENT PASSING ITS PROPERTY
text={'This is component' + this.props.componentName }
/>
</div>
);
}
}
class App extends Component {
render () {
return (
<div>
<Main componentName='Comp1' /> // Or 'Comp2'
</div>
);
}
}
}
我需要在主代码中呈现组件并传递其属性,但是我无法使其正常工作(请参见代码注释)。一个简单的
{comp}
呈现该组件,但是我需要能够相应地传递其属性。我尝试过的
{comp text={'This is component' + this.props.componentName}}
<comp text={'This is component' + this.props.componentName}/>
他们都没有工作。
最佳答案
您的组件名称必须以UpperCase字符开头。所以看起来像
import { components } from './components';
class Main extends Component {
getComponent = (name) => {
return components[name];
};
render () {
let Comp = this.getComponent(this.props.componentName);
return (
<div>
<Comp text={'This is component' + this.props.componentName }
/>
</div>
);
}
}
class App extends Component {
render () {
return (
<div>
<Main componentName='Comp1' /> // Or 'Comp2'
</div>
);
}
}
}
关于javascript - ReactJs:动态组件加载传递属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45890853/