web-dev-qa-db-fra.com

fonction d'appel sur le bouton clic réagit

J'essaye de montrer le corps différent de HTML sur le même onglet ayant deux boutons. J'ai deux boutons. Je veux montrer différents html sur deux boutons différents, pour ce faire, j'ai ajouté deux fonctions nommées xyz et abc pour le rendu html. Mais je ne comprends pas comment appeler cette fonction. Pour ce faire, j'ai ajouté un indicateur de variable. Et je ne comprends pas comment utiliser cet indicateur avec les fonctions xyz et abc. Cela devrait ressembler à quelque chose comme si le bouton abc devait appeler la fonction abc avec la fonction streamLogs et s'il s'agissait du bouton xyz, il devrait appeler la fonction xyz avec la fonction onCloud. Cette fonction onCloud et streamLogs contient l'appel api de Java.

export default class ResourceLog extends React.Component{
constructor(props) {
    super(props);
    this.state = {
        streamData: {},
        streamMessage : "",
        interval : 5000,
        showDatePicker:false,
        selectionConfigs : [
            {name:"1 Hr",cssClass:"btn btn-info btn-sm",duration:300,startTime:-1,endTime:-1,diff:3600},
            {name:"3 Hr",cssClass:"btn btn-info btn-sm",duration:300,startTime:-1,endTime:-1,diff:10800},
        ],
        params : {},
        flag: true
    }
}
streamLogs = ()=> {
       if(this.props.resource.status === "ACTIVE"){
            this.setState({"streamMessage":"loading logs.."})
               axios.instance.get("api/resources/" + this.props.resource.id+"/log/stream")
               .then((resp) => {
                   this.setState({streamData : resp.data,streamMessage:""})
               }).catch(err => {       
                   this.setState({streamMessage:""})
                   NotificationManager.error("unable to fetch logs")
               })              
       }else{
            this.setState({"streamMessage":"Resource is not Active cannot fetch/stream logs..."})              
       }
}
onCloud = () =>{

    let endTime = this.state.params.endTime;
    if(endTime === -1){
        endTime = new Date().getTime();
    }
    let startTime = this.state.params.startTime;
    if(startTime === -1){
        startTime = endTime - this.state.params.diff*1000;
    }

    let filter = this.state.params.duration;
    if(filter === -1){
        filter = "";
    }

    let params = Object.assign({},{startTime:startTime,endTime:endTime,filter:period});

    this.setState({"streamMessage":"loading stats.."});
       axios.instance.get("api/resources/" + this.props.resource.id+"/cloud/log",{params:params})
       .then((resp) => {               
           this.setState({data : resp.data,streamMessage:""})
       }).catch((error) => {
            NotificationManager.error(`Failed to fetch stats-`, "Error")
          })
}
onChange = () => {
    const flag = this.state.flag;
    let button;

    if (flag) {
        button = <abc onClick={this.streamLogs} />;
    } else {
        button = <xyz onClick={this.onCloud} />;
    }
}
render(){   
    return (
        <div>
            <button onClick={this.streamLogs}>abc</button>
            <button onClick={this.onCloud}>xyz</button>
        </div>
    )
}
abc = () =>{
    return (
            <div className="row"  style={{"margin":"15px"}}>
                <div className="col-md-12">
                    <h3 style={{display:"inline"}}>Logs
                        <span style={{marginLeft:"10px", cursor:"pointer"}} title={"Download"}><a target="_blank" href={`api/resources/${this.props.resource.id}/log`}><i className="fa fa-download"></i></a></span>
                        <span style={{marginLeft:"10px", cursor:"pointer"}} title={"Refresh"}><i onClick={this.streamLogs} className="fa fa-refresh"></i></span>
                    </h3>
                </div>
                <div className="clearfix"/>
                <br />
                <div className="col-md-12">
                    <div>{this.state.streamMessage}</div>
                    {mapObject(this.state.streamData,(k,v) => <div><pre>{v.join("\n")}</pre></div>)}
                </div>
            </div>
    );
}
xyz = () =>{
    return(
        <div className="row" style={{margin:"20px",textAlign:"center"}}>
            <div>
                <span className={this.state.selectionConfigs[0].cssClass} onClick={() =>this.updateStatsConf(this.state.selectionConfigs[0])}>{this.state.selectionConfigs[0].name}</span>
                <span style={{marginLeft:"10px"}} className={this.state.selectionConfigs[1].cssClass} onClick={() =>this.updateStatsConf(this.state.selectionConfigs[1])}>{this.state.selectionConfigs[1].name}</span>
                <span style={{marginLeft:"10px"}} className={this.state.selectionConfigs[2].cssClass} onClick={() =>this.updateStatsConf(this.state.selectionConfigs[2])}>{this.state.selectionConfigs[2].name}</span>
            </div>

        <div className="row" style={{margin:"20px"}}>
            <div className="col-md-12">
                    <div>{this.state.streamMessage}</div>
                    {mapObject(this.state.streamData,(k,v) => <div><pre>{v.join("\n")}</pre></div>)}
            </div>
        </div>
    </div>

    );
}

}

2
mayank singh

Veuillez trouver la meilleure approche à utiliser pour n’importe quel nombre de boutons. J'ai commenté aussi les méthodes indésirables.

export default class ResourceLog extends React.Component{
constructor(props) {
    super(props);
    this.state = {
        streamData: {},
        streamMessage : "",
        interval : 5000,
        showDatePicker:false,
        selectionConfigs : [
            {name:"1 Hr",cssClass:"btn btn-info btn-sm",duration:300,startTime:-1,endTime:-1,diff:3600},
            {name:"3 Hr",cssClass:"btn btn-info btn-sm",duration:300,startTime:-1,endTime:-1,diff:10800},
        ],
        params : {},
        flag: true
    }
}
streamLogs = ()=> {
       if(this.props.resource.status === "ACTIVE"){
            this.setState({"streamMessage":"loading logs.."})
               axios.instance.get("api/resources/" + this.props.resource.id+"/log/stream")
               .then((resp) => {
                   this.setState({streamData : resp.data,streamMessage:"", show: "abc"})
               }).catch(err => {       
                   this.setState({streamMessage:""})
                   NotificationManager.error("unable to fetch logs")
               })              
       }else{
            this.setState({"streamMessage":"Resource is not Active cannot fetch/stream logs..."})              
       }
}
onCloud = () =>{

    let endTime = this.state.params.endTime;
    if(endTime === -1){
        endTime = new Date().getTime();
    }
    let startTime = this.state.params.startTime;
    if(startTime === -1){
        startTime = endTime - this.state.params.diff*1000;
    }

    let filter = this.state.params.duration;
    if(filter === -1){
        filter = "";
    }

    let params = Object.assign({},{startTime:startTime,endTime:endTime,filter:period});

    this.setState({"streamMessage":"loading stats.."});
       axios.instance.get("api/resources/" + this.props.resource.id+"/cloud/log",{params:params})
       .then((resp) => {               
           this.setState({data : resp.data,streamMessage:"", show: "abc"})
       }).catch((error) => {
            NotificationManager.error(`Failed to fetch stats-`, "Error")
          })
}
// onChange = () => {
//     const flag = this.state.flag;
//     let button;

//     if (flag) {
//         button = <abc onClick={this.streamLogs} />;
//     } else {
//         button = <xyz onClick={this.onCloud} />;
//     }
// }
getBody = () => {
    if(this.state.show == "abc"){
        return (
            <div className="row"  style={{"margin":"15px"}}>
                <div className="col-md-12">
                    <h3 style={{display:"inline"}}>Logs
                        <span style={{marginLeft:"10px", cursor:"pointer"}} title={"Download"}><a target="_blank" href={`api/resources/${this.props.resource.id}/log`}><i className="fa fa-download"></i></a></span>
                        <span style={{marginLeft:"10px", cursor:"pointer"}} title={"Refresh"}><i onClick={this.streamLogs} className="fa fa-refresh"></i></span>
                    </h3>
                </div>
                <div className="clearfix"/>
                <br />
                <div className="col-md-12">
                    <div>{this.state.streamMessage}</div>
                    {mapObject(this.state.streamData,(k,v) => <div><pre>{v.join("\n")}</pre></div>)}
                </div>
            </div>
        );
    }else if(this.state.show == "xyz"){
        return(
            <div className="row" style={{margin:"20px",textAlign:"center"}}>
                <div>
                    <span className={this.state.selectionConfigs[0].cssClass} onClick={() =>this.updateStatsConf(this.state.selectionConfigs[0])}>{this.state.selectionConfigs[0].name}</span>
                    <span style={{marginLeft:"10px"}} className={this.state.selectionConfigs[1].cssClass} onClick={() =>this.updateStatsConf(this.state.selectionConfigs[1])}>{this.state.selectionConfigs[1].name}</span>
                    <span style={{marginLeft:"10px"}} className={this.state.selectionConfigs[2].cssClass} onClick={() =>this.updateStatsConf(this.state.selectionConfigs[2])}>{this.state.selectionConfigs[2].name}</span>
                </div>

            <div className="row" style={{margin:"20px"}}>
                <div className="col-md-12">
                        <div>{this.state.streamMessage}</div>
                        {mapObject(this.state.streamData,(k,v) => <div><pre>{v.join("\n")}</pre></div>)}
                </div>
            </div>
        </div>

        );
    }else{
        <h1> please click a BUtton </h1>
    }
}
render(){   
    return (
        <div>
            <button onClick={this.streamLogs}>abc</button>
            <button onClick={this.onCloud}>xyz</button>
            {this.getBody()}
        </div>
    )
}
    // abc = () =>{

    // }
    // xyz = () =>{

    // }
}

Ainsi, chaque fois que vous récupérez les données avec succès, vous déclenchez un affichage d'état indiquant ce qu'il faut afficher dans la méthode de contrôle du corps getBody() pour tout le traitement de l'affichage. même la source semble bien organisée.

0
karthik