react 动态显示组件_React:如何在点击时显示其他组件
react 动态显示组件In many scenarios you want to display a completely different component inside a screen, when a button or link is clicked.在许多情况下,当您单击按钮或链接时,您希望在屏幕内显示完全不同的组件。Think about a navigation st...
react 动态显示组件
In many scenarios you want to display a completely different component inside a screen, when a button or link is clicked.
在许多情况下,当您单击按钮或链接时,您希望在屏幕内显示完全不同的组件。
Think about a navigation structure, for example.
例如,考虑一下导航结构。
How can you do so?
你该怎么做?
In this example I’m managing the state centralized in the App component.
在此示例中,我管理集中在App组件中的状态。
First, attach a click event to a component:
首先,将click事件附加到组件:
import React from 'react'
const AddTripButton = props => {
return <button onClick={props.addTrip}>Add a trip</button>
}
export default AddTripButton
Then in the App component, handle the addTrip event by assigning it the triggerAddTripState method:
然后在App组件中,通过为它分配triggerAddTripState方法来处理addTrip事件:
<AddTripButton addTrip={this.triggerAddTripState} />
In triggerAddTripState you edit the state of the component:
在triggerAddTripState您可以编辑组件的状态:
class App extends Component {
constructor(props) {
super(props)
this.state = { isEmptyState: true }
}
triggerAddTripState = () => {
this.setState({
...this.state,
isEmptyState: false,
isAddTripState: true
})
}
}
See, here I create a default state, which contains isEmptyState: true. When the triggerAddTripState method is run, the state is edited so that property is set to false, and a new isAddTripState property is set to true.
看,这里我创建一个默认状态,其中包含isEmptyState: true 。 运行triggerAddTripState方法时,将编辑状态,以便将属性设置为false,并将新的isAddTripState属性设置为true。
Now in the JSX we can use those 2 state properties to show and hide parts of the component by using this syntax:
现在在JSX中,我们可以使用以下2种状态属性来显示和隐藏组件的某些部分:
render() {
return (
<div>
{this.state.isEmptyState && <AddTripButton addTrip={this.triggerAddTripState} />}
{this.state.isAddTripState && <AnotherComponent />}
</div>
)
}
翻译自: https://flaviocopes.com/react-show-different-component-on-click/
react 动态显示组件
更多推荐
所有评论(0)