我有一个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}/>
他们都没有奏效。帮助赞赏。
答案 0 :(得分:1)
组件名称需要以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>
);
}
}
}