我的目标是在不更改其URL路径名的情况下呈现Component
。当用户单击链接时,此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'))
为了更好地演示,这里是指向代码笔的链接:
可以通过将索引保持在状态然后基于当前索引进行呈现来简化代码。这是我稍微简化的解决方案:
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"));
[<a>
标记默认情况下将重新加载页面。
您可以将事件对象从onClick动作(onClick={(e) => this.handleClick(e,'three')}
)传递到handleClick方法,在该方法中,使用e.preventDefault()
阻止重新加载页面。
您还可以使用React Router从使用默认HTML <a>
切换到<Link>
。链接组件正在渲染<a>
,但单击后不会重新加载整个页面。