1
我有ReactJS組件庫,如以下代碼: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}/>
他們沒有工作。幫助讚賞。
你是怎麼渲染App的? 'this.props.componentName'的價值是什麼? – Dekel
@Dekel,'this.props.componentName'是'Comp1'或'Comp2'。使用初始渲染組件更新了代碼。 – Mendes
@Mendes,'export components'工作嗎?爲什麼不使用三元來檢查應顯示哪個組件? – Andrew