reactjs - 动态添加新组件
问题描述
我在父组件中,我正在尝试通过单击按钮动态添加新组件。我将只粘贴必要的代码,因为我的文件很大。
所以在它下面我们说父组件:
export default class Parent extends Component {
constructor(props) {
super(props);
this.state = {
conditions: [{attribute: '', operator: '', value: ''}]
}
}
addCondition = (e) => {
this.setState((prevState) => ({
conditions: [...prevState.conditions, { attribute: '', operator: '',value: '' }],
}));
}
render() {
let {conditions} = this.state
return(
<Row>
<TextButton label='Add Child' onClick={(e) => {this.addCondition}} flat={true} />
</Row>
<Row>
<ChildElement conditions={conditions} />
</Row>
)
}
}
这是我要动态渲染的 ChildElement:
export class ChildElement extends Component {
constructor(props) {
super(props);
this.state = {
attribute: '',
operator: '',
action: '',
};
}
render() {
return (
this.props.conditions.map((val, idx)=> {
let attributeId = `attributeId-${idx}`,
operatorId = `operatorId-${idx}`,
valueId = `valueId-${idx}`
return (
<Row>
<Col >
<Dropdown id={attributeId} />
</Col>
<Col >
<Dropdown id={operatorId} />
</Col>
<Col>
<Dropdown id={valueId} />
</Col>
</Row>
);
})
);
}
}
加载父组件时出现错误:
Uncaught Error: ConditionElement.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
解决方案
我会在这里得到一个疯狂的猜测,因为我没有看到整个代码。
您正在导入,ChildElement
就好像它是一个default export
但实际上它是一个命名的导出。
这
export class ChildElement
应该这样导入:
import {ChildElement} from './path'
并不是:
import ChildElement from './path'
推荐阅读
- python - 从任何地方激活 Python venv
- javascript - 如何识别点(xy)在svg组几何元素内
- ios - @import geolocator_apple:找不到模块“geolocator_apple”
- laravel - 向 Laravel web.php 路由发送 POST 请求
- prestashop - 如何处理带有 div 元素的 CLS 分数?(网络生命体征)
- c# - 在 post-request 中设置带有参数的 accept-header
- apache-spark - 如何在 Spark3 中获取 **add_months** Spark2 行为
- python - How can i calculate pct changes between groups of colums efficiently?
- http - IIS redirect www to non www using https
- css - v-menu background become transparent and overlay navbar Vuetify