我有一个数组列表,我想将字符串与组件名称匹配,这可能吗?我试过这个https://codesandbox.io/s/lpzq3jvjm7
function App() {
const obj = {
name: "Name"
};
const capitalize = (s) => {
if (typeof s !== 'string') return ''
return s.charAt(0).toUpperCase() + s.slice(1)
}
return (
<div className="App">
{React.createElement(capitalize(obj.name), {
name: "james"
})}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
似乎不起作用,有什么线索吗?
最佳答案
很难判断您实际上遇到了什么错误,因为您没有名为 Name
的组件。简单修复?
function Name(props) {
return props.name
}
function App() {
const obj = {
name: Name
};
return (
<div className="App">
{React.createElement(obj.name, {
name: "james"
})}
</div>
);
}
在页面上打印 james
。
更新
您缺少一些东西..首先导入您的组件
import Name from './Name'
并且在 Name.js
中您缺少 react 导入
import React from 'react'
export default ({ name }) => <h1>my name is {name}</h1>;
并确保将 Name
的实际值设置为您的对象,而不是字符串“Name”
const obj = {
name: Name
};
关于javascript - 从字符串创建 react 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55035897/