I have a Component
with an onClick
event. This event sets in my global state
some boolean
to true
. How can, depending on this boolean
render/hide another component
?
I could write something like (pseudocode!)
<ParentCompononet
conditionalRendering(props) {
if(props.boolean) {
<ConditionalComponent />
} else {
null
}
render () {
return (
{ conditionalRendering }
)
/>
Not sure if that would be the right way
Once you connect
the boolean value to props, you could just do something like this:
const MyComponent = (props) => {
return { props.myBool && <MyChildComponent /> };
}
or slightly more verbose:
const MyComponent = (props) => {
if (props.myBool) {
return <MyChildComponent />;
} else {
return null;
}
}
Assuming you have configured react-redux propely, This might be the one you are looking for.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.