gpt4 book ai didi

reactjs - 无法在 react 组件中动态创建元素

转载 作者:行者123 更新时间:2023-12-03 13:18:48 24 4
gpt4 key购买 nike

我无法动态创建 React 组件。我看到空白页面,没有任何错误,代码如下。

1) 尝试创建一个名为“PieChart”的元素

2)以下是我在控制台中看到的两个错误。

1. Warning: <PieChart /> is using incorrect casing. Use PascalCase for    
React components, or lowercase for HTML elements.

2. Warning: The tag <PieChart/> is unrecognized in this browser. If you
meant to render a React component, start its name with an
uppercase letter.

3)我已经在使用 Pascal 案例“PieChart”

import PieChart from "../component/PieChart";
class App extends Component {

render() {
const GraphWidget = React.createElement("PieChart");
return (
<div>
{GraphWidget}

</div>
)
}


}


export default App;

最佳答案

来自createElement documentation :

Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span'), a React component type (a class or a function), or a React fragment type.

您正在尝试使用React组件类型,因此您不能使用字符串,您需要直接使用该类:

const GraphWidget = React.createElement(PieChart);

如果您的目标是将字符串映射到组件,您可以使用字典创建简单的映射:

const components = {
PieChart: PieChart
...
};

const GraphWidget = React.createElement(components['PieChart']);

关于reactjs - 无法在 react 组件中动态创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50120269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com