如何在条件渲染中添加条件渲染

时间:2018-01-31 03:00:50

标签: javascript reactjs

我有点新的反应我只是想知道如何在我的登录页面中添加条件渲染,只要用户名和密码与api用户名和密码匹配,在点击提交按钮后它应该给我新的成分

//here is api
const api ='http://localhost:3000/api/login';
//Login Component
export class Login extends Component {
state = {
            username: '',
            password: '',
            confirmuser:'',
            confirmpass:'',
        };
    componentDidMount() {
        axios.get(api).then(response => {
            let number = response.data.username;
            console.log(response);
            let number2 = response.data.password;
             this.setState({ confirmuser:number});
             this.setState({ confirmpass: number2 });
        })
    .catch((err)=>{
        console.log('Looks like something went wroong ',err);
    });
    }
        //HandleClick Method
            handleClick=()=>{
            const username = this.state.username;
            const password= this.state.password;
            const confirmuser=this.state.confirmuser;
            const confirmpass=this.state.confirmpass;
            console.log(confirmuser);
            console.log(username);
            console.log(password);
            console.log(confirmpass);
            if (username == confirmuser && password == confirmpass ){  
                console.log(`username is ${username}`);
            }
            else{
                console.log('Please enter right username or password');
            }
        };
        
     //Rendaring the elements from material-ui
        render() {
            return (
                <div>
                        <div>
                            <AppBar
                                title="Login"
                            />
                            <TextField
                                hintText="Enter your Username"
                                floatingLabelText="Username"
                                onChange={(event, newValue) => this.setState({ username: newValue })}
                            />
                            <br />
                            <TextField
                                type="password"
                                hintText="Enter your Password"
                                floatingLabelText="Password"
                                onChange={(event, newValue) => this.setState({ password: newValue })}
                            />
                            <br /> 
                            <RaisedButton label="Submit" primary={true} style={style} onClick={ (event) => this.handleClick(event)} />
                        </div>
                </div>
            );
        }
    };

单击按钮提交后如何呈现

2 个答案:

答案 0 :(得分:4)

有两种方法如果要重定向到另一个组件。然后使用react-router 4这样做。使用this

     handleClick=()=>{
        const username = this.state.username;
        const password= this.state.password;
        const confirmuser=this.state.confirmuser;
        const confirmpass=this.state.confirmpass;
        console.log(confirmuser);
        console.log(username);
        console.log(password);
        console.log(confirmpass);
        if (username == confirmuser && password == confirmpass ){  
               this.props.history.push({ pathname: '/yourcomponent',});
        }
        else{
            console.log('Please enter right username or password');
        }
    };

将您的组件包装在withRouter HOC中以使其正常工作。

否则,如果要在同一页面中呈现组件(更简单的方法)。 然后这样做。

       constructor(props){
         super(props);
         this.state={
           loginSuccess:false
         }
     }


   handleClick=()=>{
        const username = this.state.username;
        const password= this.state.password;
        const confirmuser=this.state.confirmuser;
        const confirmpass=this.state.confirmpass;
        console.log(confirmuser);
        console.log(username);
        console.log(password);
        console.log(confirmpass);
        if (username == confirmuser && password == confirmpass ){  
            this.setState({loginSuccess:true});
        }
        else{
            console.log('Please enter right username or password');

        }
    };

     renderComp(){
       if(this.state.loginSuccess===true){
          return(<YourComponent/>);
        }
        else{
            return(<div>Incorrect UserName or Password</div>)
        }
     }

 //Rendaring the elements from material-ui
    render() {
        return (
            <div>
                    <div>
                        <AppBar
                            title="Login"
                        />
                        <TextField
                            hintText="Enter your Username"
                            floatingLabelText="Username"
                            onChange={(event, newValue) => this.setState({ username: newValue })}
                        />
                        <br />
                        <TextField
                            type="password"
                            hintText="Enter your Password"
                            floatingLabelText="Password"
                            onChange={(event, newValue) => this.setState({ password: newValue })}
                        />
                        <br /> 
                        <RaisedButton label="Submit" primary={true} style={style} onClick={ (event) => this.handleClick(event)} />
                    </div>
                       //change here
                         {this.renderComp()}

            </div>
        );
    }
};

答案 1 :(得分:0)

一般来说,我总体上有两种方法可以进行条件渲染

<强> 1。使用返回JSX元素的函数

请参阅Sujit答案。

renderComp(){
   if(this.state.loginSuccess===true){
      return(<YourComponent/>);
    }
    else{
        return(<div>Incorrect UserName or Password</div>)
    }

}

然后在render方法中,只需调用它:

{this.renderComp}

<强> 2。使用内联条件

您可以在您需要的部分内容中在您的渲染方法中内联。 例如:

{this.state.loginSuccess? <SuccessComponent/> : <ErrorComponent/>}