我目前正在编写可在两个视图(图形和列表)之间切换的功能。两个是视图容器的类的名称。
toggleGraphView() {
const two = document.getElementsByClassName('two')[0];
two.innerHTML = '<span>Graph View!</span>'
}
toggleListView() {
const two = document.getElementsByClassName('two')[0];
two.innerHTML = "<ShotLog shotLog={this.state.shotLog}/>"
}
该组件可以很好地切换到图形视图文本(“图形视图!”),但是当我尝试切换回列表视图时,什么也没得到。触发toggleListView之后,在chrome工具中,两个容器包含<shotlog shotlog="{this.state.shotLog}/"></shotlog>
。我需要它看起来像<ShotLog shotLog={this.state.shotLog}/>
以便正确传递道具。
我不确定多余的报价来自哪里。有任何想法吗?
您不能通过使用JSX将它们放入字符串中来创建React组件,您的代码可以缩短为以下内容:
this.state.showGraph ? <span>Graph View!</span> : <ShotLog shotLog={this.state.shotLog} />
使用三元条件,您可以根据变量的值来决定要呈现的内容, showGraph
showGraph
将存储在组件的状态中,可通过进行访问this.state
,当您想更改状态中某物的值时,您必须调用setState
,这将导致您的组件重新呈现屏幕上的所有内容并向您显示所需的内容
工作示例:
class ShotLog extends React.Component {
render() {
return <div>Hi I'm a ShotLog</div>
}
}
class App extends React.Component {
constructor(props){
super(props)
this.state = { showGraph: true }
}
handleClick = ev => {
this.setState({ showGraph: !this.state.showGraph })
}
render() {
return (
<div>
{this.state.showGraph ?
<span>Graph View!</span>
:
<ShotLog />}
<button onClick={this.handleClick}>Switch me !</button>
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('react')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>
<div id="react"></div>
您可以在以下官方文档中找到JSX的基础知识:https : //reactjs.org/docs/introducing-jsx.html
您可以在此处了解有关组件状态的更多信息:https : //reactjs.org/docs/state-and-lifecycle.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句