我有以下代码-我想更改单击按钮时呈现的react组件。但是,单击按钮不会执行任何操作。这是父类:
export default class SupportsContent extends React.Component {
currentPage = "userSupportsList";
goToPage = page => {
this.currentPage = page;
}
render() {
let content = "";
if (this.currentPage === "userSupportsList") {
content = <UserSupportsList goToPage={this.goToPage} />
} else if (this.currentPage === "chooseNewSupport") {
content = <ChooseNewSupport goToPage={this.goToPage} />
} else if (this.currentPage === "editSupport") {
content = <EditSupport goToPage={this.goToPage} />
}
return (
<Grid>
{content}
</Grid>
);
}
}
我有以下子组件定义:
function UserSupportsList(props) {
return (
<ListItem button onClick={function () {props.goToPage("chooseNewSupport");}}></ListItem>
);
}
function ChooseNewSupport(props) {
return (
<p>Choose New Support</p>
);
}
function EditSupport(props) {
return (
<p>Edit Support</p>
);
}
答案 0 :(得分:0)
React根据两个条件来更新组件:如果组件属性发生更改,或者使用this.setState
函数来更新状态。
我建议您编辑组件以使用状态而不是变量:
class SupportsContent extends Component {
state = {
currentPage: "userSupportsList"
}
goToPage = page => this.setState({ currentPage: page })
render() {
let content = "";
if (this.state.currentPage === "userSupportsList") {
content = <UserSupportsList goToPage={this.goToPage} />
} else if (this.state.currentPage === "chooseNewSupport") {
content = <ChooseNewSupport goToPage={this.goToPage} />
} else if (this.state.currentPage === "editSupport") {
content = <EditSupport goToPage={this.goToPage} />
}
return (
<Grid>
{content}
</Grid>
);
}
}