javascript - 在不更改路由路径的情况下渲染多个组件
问题描述
Component
我的目标是在不更改其 url 路径名的情况下呈现 a 。这Component
负责components
在用户单击链接时呈现其他三个孩子。我的代码正在运行,但我认为这不是正确的方法。我的问题是:实现这一点的最佳方法是什么。下面是我的代码:
const ComponentOne = () => {
return (
<div><h1>Component 1</h1></div>
)
}
const ComponentTwo = () => {
return (
<div><h1>Component 2</h1></div>
)
}
const ComponentThree = () => {
return (
<div><h1>Component 3</h1></div>
)
}
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
linkName: 'three'
};
this.renderList = <ComponentThree/>;
}
handleClick = (linkName) => {
if (linkName === 'one') {
this.renderList = <ComponentOne/>;
this.setState({ linkName });
} else if (linkName === 'two') {
this.renderList = <ComponentTwo />;
this.setState({ linkName });
} else {
this.renderList = <ComponentThree />;
this.setState({ linkName });
}
return this.renderList;
};
render() {
return (
<div>
<ul>
<li><a
className={this.state.linkName === 'one' ? 'active' : ''}
onClick={() => this.handleClick('one')}>
Component 1
</a></li>
<li><a
className={this.state.linkName === 'two' ? 'active' : ''}
onClick={() => this.handleClick('two')}>
Component 2
</a></li>
<li><a
className={this.state.linkName === 'three' ? 'active' : ''}
onClick={() => this.handleClick('three')}>
Component 3
</a></li>
</ul>
{this.renderList}
</div>
)
}
}
ReactDOM.render(<Header/>, document.querySelector('#root'))
为了更好地展示这里是codepen的链接:
解决方案
您可以通过将索引保持在状态然后根据当前索引进行渲染来简化您的代码。这是我稍微简化的解决方案:
https://codepen.io/olavih/pen/zYGobaV
return (
<div>
<h1>Component 1</h1>
</div>
);
};
const ComponentTwo = () => {
return (
<div>
<h1>Component 2</h1>
</div>
);
};
const ComponentThree = () => {
return (
<div>
<h1>Component 3</h1>
</div>
);
};
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
linkIndex: 3
};
}
handleClick = linkIndex => {
this.setState({ linkIndex });
};
render() {
return (
<div>
<ul>
<li>
<a
className={this.state.linkIndex === 1 ? "active" : ""}
onClick={() => this.handleClick(1)}
>
Component 1
</a>
</li>
<li>
<a
className={this.state.linkIndex === 2 ? "active" : ""}
onClick={() => this.handleClick(2)}
>
Component 2
</a>
</li>
<li>
<a
className={this.state.linkIndex === 3 ? "active" : ""}
onClick={() => this.handleClick(3)}
>
Component 3
</a>
</li>
</ul>
{this.state.linkIndex === 1 && <ComponentOne />}
{this.state.linkIndex === 2 && <ComponentTwo />}
{this.state.linkIndex === 3 && <ComponentThree />}
</div>
);
}
}
ReactDOM.render(<Header />, document.querySelector("#root"));
推荐阅读
- asp.net-mvc - 如何在数据表行中插入按钮?
- python-3.x - 根据另一列中的分箱值在新列中创建标志
- http - Microsoft AD 应用程序验证失败:“microsoft-identity-association.json 的内容长度未设置或无效”
- python - Python:通过添加累积股息并取复合年增长率(CAGR)来计算总回报
- python - 四张表之间的SQL查询
- ios - 未定义符号:_OBJC_CLASS_$_FBSDKBasicUtility
- c# - 使用不同类型的节点从 JSON 创建类
- c# - 无法连接到 Linux 计算机上的 GRPC 服务
- apache-kafka - Kafka 增加处理超时消息
- javascript - 在 PaperJS 中查找闭合路径(多边形)的质心