有条件的渲染Redux和反应
问题描述:
我有一个Component
与onClick
事件。此事件设置在我的global state
一些boolean
至true
。怎么可以,取决于这个boolean
渲染/隐藏另一个component
?有条件的渲染Redux和反应
我可以写类似
<ParentCompononet
conditionalRendering(props) {
if(props.boolean) {
<ConditionalComponent />
} else {
null
}
render() {
return (
{ conditionalRendering }
)
/>
不知道这将是正确的方式
答
一旦你connect
布尔值的道具,你可能只是做这样的事情(伪!):
const MyComponent = (props) => {
return { props.myBool && <MyChildComponent /> };
}
或稍微详细:
const MyComponent = (props) => {
if (props.myBool) {
return <MyChildComponent />;
} else {
return null;
}
}
答
假设您已配置react-redux propely,这可能是您正在寻找的那个。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as Actions from '../../actions';
class User extends Component {
constructor(props) {
super(props);
}
click=()=>{
this.props.actions.someEvent();
}
render() {
return (
<div>
(this.props.useravailable) ? <div>Hello world!</div> : <div/>
</div>
);
}
}
Login.PropTypes = {
useravailable: PropTypes.bool.isRequired,
actions: PropTypes.object.isRequired
}
let mapStateToProps = (state,props) => {
return {
useravailable: state.user
}
}
let mapDispatchToProps = (dispatch) => {
return {
actions:bindActionCreators(Actions,dispatch)
};
}
export default connect(mapStateToProps,mapDispatchToProps)(User);
可能*太*宽,因为你目前有它:)你能够'连接'状态变量的组件'道具'? –
@DavinTryon我认为是的,是的 – Stophface