之前有人问过这个问题,但这些解决方案似乎对我不起作用……也许是因为我有条件地渲染?我的想法是我可以选择供用户单击,然后在单击时呈现适当的组件。所以我想在用户做出选择时有条件地将组件的名称注入到标签中。这是一个相当小的例子:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import RaisedButton from 'material-ui/RaisedButton';
import { setData } from '../../actions/data';
import * as mathUtils from '../../mathUtils';
class MyParentClass extends Component {
constructor(props) {
super(props);
this.handleChoice = this.handleChoice.bind(this);
}
handleChoice({ topic, user }) {
const id = `${Date.now()}-${mathUtils.uuidv4()}`;
this.props.setData({ topic, id, user });
}
render() {
const { id, currentUser } = this.props;
const Topic = this.props.topic;
return (
id
? <Topic />
: <RaisedButton
role="button"
primary={true}
label="NumberOne"
onClick={() => this.handleChoice({
topic: 'NumberOne',
user: currentUser
})
}
/>
<br />
<RaisedButton
role="button"
primary={true}
label="NumberTwo"
onClick={() => this.handleChoice({
topic: 'NumberTwo',
user: currentUser
})
}
/>
);
}
}
MyParentClass.propTypes = {
id: PropTypes.string,
topic: PropTypes.string,
setData: PropTypes.func.isRequired,
currentUser: PropTypes.object.isRequired
};
MyParentClass.defaultProps = {
id: null,
topic: null
};
export default connect(
({ session, data }) => ({
currentUser: session.currentUser,
id: data.id,
topic: data.topic
}),
{ setData }
)(MyParentClass);
对于此代码,我在控制台中收到两个不同的错误,它们似乎彼此不一致。第一个是 Warning: <NumberOne /> is using uppercase HTML. Always use lowercase HTML tags in React.
第二个是 Warning: The tag <NumberOne> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
我有理由相信我只是没有将正确的逻辑应用于我的应用程序,但我不确定还有什么方法可以完成所需的行为。
原文由 TrivialCase 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以直接设置
element
而不是string
。首先import
你的组件像然后,在你的
onClick
中设置相应的组件您的其余代码与上述更改一样应该适合您。