Как передать состояние истина или ложь от ребенка к родителю - PullRequest
0 голосов
/ 29 мая 2019

У меня есть два компонента, один родитель (виджеты) и другой сын (телефоно). Компонент "Telefono" имеет статус notInCall, и с его помощью я рисую или нет определенную часть кода. С другой стороны, у меня есть функция showComponent(), которая находится в родительском элементе, с которым я показываю или нет дочерний компонент (Telefono), и два других компонента. Мне нужно восстановить от родителя, в the showComponent() функция текущего состояния (true или false) notInCall, но я не знаю, как это сделать.

Редактировать : Мне кажется, я не очень хорошо объяснил. В ребенке я использую условное this.state.notInCall, чтобы показать или нет часть кода. Мне нужно передать ответ true или false родителю. Если {this.state.notInCall ? (some code) : (another code)}. Если this.state.notInCall для ребенка - true, сделайте одно, а если false - другое

.

Это мой родительский компонент (виджеты)

class Widgets extends Component {   
    constructor(props) {
        super(props);
        this.state = {
            componente: 1,
            //notInCall: false,
        };
        this.showComponent = this.showComponent.bind(this);
    }

    showComponent(componentName) {
        /*this.setState({
            notInCall: false,
        });*/
        if(this.state.notInCall === false){
            this.setState({
                componente: Telefono,
                addActive: Telefono,
            });
            alert(this.state.notInCall + ' running? Componente:' + componentName);
            console.log(this.state.notInCall);
        }else{
            alert('verdad');
            this.setState({
                componente: componentName,
                addActive: componentName,
            });            
        }
        console.log(this.state.notInCall);
    }

    renderComponent(){
        switch(this.state.componente) {
            case "ChatInterno":
                return <ChatInterno />
            case "HistorialLlamadas":
                return <HistorialLlamadas />
            case "Telefono":
            default:
                return <Telefono showComponent={this.showComponent}/>
        }
    }

    render(){
        return (
            <div id="bq-comunicacion">
                <nav>
                    <ul>
                        <li><button onClick={() => this.showComponent('Telefono')} id="mn-telefono" className={this.state.addActive === 'Telefono' ? 'active' : ''}><Icon icon="telefono" className='ico-telefono'/></button></li>
                        <li><button onClick={() => this.showComponent('ChatInterno')} id="mn-chat" className={this.state.addActive === 'ChatInterno' ? 'active' : ''}><Icon icon="chat-interno" className='ico-chat-interno'/></button></li>
                        <li><button onClick={() => this.showComponent('HistorialLlamadas')} id="mn-llamadas" className={this.state.addActive === 'HistorialLlamadas' ? 'active' : ''}><Icon icon="historial-llamadas" className='ico-historial-llamadas'/></button></li>
                    </ul>
                </nav>
                <div className="content">
                    { this.renderComponent() }
                </div>
            </div>
        );
    }
}

Это мой дочерний компонент (Telefono)

class Telefono extends Component {
    constructor(props) {
        super(props);

        this.inputTelephone = React.createRef();

        ["update", "reset", "deleteClickNumber", "closeAlert", "handleKeyPress",].forEach((method) => {
            this[method] = this[method].bind(this);
        });

        this.state = this.initialState = {
            notInCall: true,
            isRunning: false,
        };
    }

    phoneCall(e){
        e.preventDefault();
        this.props.showComponent(this.state.notInCall);

        if(this.state.inputContent.length < 2){
            this.setState({
                warningEmptyPhone: true,
            });

            this.change = setTimeout(() => {
                this.setState({
                    warningEmptyPhone: false
                })
            }, 5000)
        }else if(this.state.inputContent.length >= 2 ){
            this.setState({
                notInCall: !this.state.notInCall,
                isRunning: !this.state.isRunning,
                componente: 'Telefono',
            }, 
                () => {
                    this.state.isRunning ? this.startTimer() : clearInterval(this.timer);
                    //console.log(this.componente);
                });
        }
    }

    render(){
        return(
            <div className="pad sb-content">
                {this.state.notInCall
                    ? (
                        <>
                        <div className="dial-pad">
                            <div className="digits">
                                <Numbers numbers={this.state.numbers}
                                />
                            </div>
                        </div>
                        <div className="btn-call call" onClick={this.phoneCall.bind(this)}>
                            <Icon icon="telefono" className='ico-telefono'/>
                            <span>LLAMAR</span>
                        </div>
                        </>
                    )
                    : (
                        <div className="call-pad">
                            <div id="ca-number" className="ca-number">{this.state.inputContent}</div>
                            <TimeElapsed id="timer" timeElapsed={timeElapsed}/>
                        </div>    

                    )}
            </div>
        );
    }
}

Спасибо за помощь

Ответы [ 2 ]

1 голос
/ 29 мая 2019

Вы можете создать дескриптор в родительском, например:


handleNotInCall (notInCall) {
  // handle here
}

И передайте эту ручку ребенку:

<Telefono handleNotInCall={this.handleNotInCall} />

В детстве ты звонишь так:


this.props.handleNotInCall(<param here>)

UPDATE

на родителя: На родителя:

  • поставить notInCall в состояние
  • создать дескриптор для notInCall
  • пропуск для ручки ребенка и состояния
// state
this.state = {
  componente: 1,
  notInCall: false,
};
// create a handle
handleNotInCall (notInCall) {
  this.setState({notInCall});
}
// pass both for child
<Telefono handleNotInCall={this.handleNotInCall} notInCall={this.state.notInCall}/>

У ребенка, где вы делаете:

this.setState({
  notInCall: !this.state.notInCall,
  isRunning: !this.state.isRunning,
  componente: 'Telefono',
})
// change for
this.props.handleNotInCall(!this.props.notInCall)
this.setState({
  isRunning: !this.state.isRunning,
  componente: 'Telefono',
})

// where you use for compare 
this.state.notInCall ? 
// change for:
this.props.notInCall ?
0 голосов
/ 29 мая 2019

Если я правильно понял вашу проблему, ответ Марчелло Сильвы будет правильным.

Скажем, у вас есть это:

class Parent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            childAvailable: true,
        };
    }

    handleAvailability = status => {
        this.setState({ childAvailable: status });
    }

    render() {
        const { childAvailable } = this.state;

        if (!childAvailable) {
            return (...); // display whatever you want if children not available
        } else {
            return (
                <div>
                    {children.map(child => {
                        <Children
                            child={child}
                            statusHandler={this.handleAvailability}
                        />
                    }
                </div>
            );
        }
    }
}

и

class Children extends React.Component {
    constructor(props) {
         super(props);

         this.state = {
             available: true,
         };
    }

    handleClick = e => {
        const status = !this.state.available;
        this.setState(prevState => { available: !prevState.available });

        // if you call the handler provided by the parent here, with the value
        // of status, it will change the state in the parent, hence
        // trigger a re render conditionned by your value
        this.props.statusHandler(status);
    }

    render() {
        return (
            <div>
                <button onClick={this.handleClick}>Click me to change status</button>
            </div>
        );
    }
}

Делать этовызовет функцию, которую вы передали в качестве опоры своим детям в ваших родителей.Эта функция устанавливает ваше состояние и, следовательно, запускает рендеринг после его установки, поэтому вы будете рендерить все, что захотите, учитывая новое значение childAvailable.

EDIT : После просмотра комментария к указанному ответу я хотел бы добавить, что вы, конечно, можете вызвать свой метод handleClick из ваших условий на this.state.notInCall.

...