У меня есть простой компонент React с именем Row, который имеет два других компонента:
ViewRow фактическая строка, которую может видеть пользователь.SubRow, который скрыт под ViewRow.Здесь я пытаюсь добавить onClick к компоненту ViewRow, чтобы при нажатии на него компонент SubRow менял свое отображение со скрытого, чтобы пользователь мог видеть больше данных о человеке.
Я попробовал простую кнопку с тем же onClick, и все работает нормально; Он выполняет console.info тестовой строки и при использовании setState также успешно меняет состояние. Когда я пытаюсь передать его компоненту ViewRow, он просто ничего не делает, даже не ломает мой код.
Компонент строки
class Row extends Component {
constructor(props) {
super(props);
this.state = {
isActive: false
};
this.toggleActive = this.toggleActive.bind(this);
};
toggleActive(e) {
// let currentState = this.state.isActive;
// this.setState({ isActive: !currentState });
console.info("button pressed: ")
};
render() {
console.info(this.props);
return (
<React.Fragment>
{/*<button onClick = {this.toggleActive.bind(this)}> click </button>*/}
<ViewRow
id = {this.props.person.id}
fname = {this.props.person["First Name"]}
lname = {this.props.person["Last Name"]}
birthdate = {this.props.person.birthdate}
email = {this.props.person.email}
gender = {this.props.person.gender}
address = {this.props.person.address}
onClick = {this.toggleActive}
/>
<SubRow person = {this.props.person} />
</React.Fragment>
);
}
};
Компонент ViewRow
class ViewRow extends Component {
render() {
return (
<tr className = "row">
<ColData className = "first" data = {this.props.id} />
<ColData data = {this.props.fname} />
<ColData data = {this.props.lname} />
<ColData data = {this.props.birthdate} />
<ColData data = {this.props.email} />
<ColData data = {this.props.gender} />
<ColData data = {this.props.address} />
</tr>
);
}
};
Компонент подстроки
class SubRow extends Component {
render() {
return (
<tr className = "hidden">
<td colSpan = "7">
<div>
<SubRowContent
isActive = {this.props.isActive}
company = {this.props.person.company}
emplid = {this.props.person["Employee ID"]}
/>
</div>
</td>
</tr>
);
}
};
Я ожидаю, что функция onclick изменит состояние, чтобы в конечном итоге я мог использовать ее для переключения отображения компонента SubRow.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Просто передайте переменную состояния своему компоненту, чтобы вы могли отображать ее, когда вам нужно.
class Row extends Component {
constructor(props) {
super(props);
this.state = {
isActive: false
};
this.toggleActive = this.toggleActive.bind(this);
};
toggleActive(e) {
// let currentState = this.state.isActive;
this.setState({ isActive: !currentState });
console.info("button pressed: ")
};
render() {
console.info(this.props);
return (
<React.Fragment>
{/*<button onClick = {this.toggleActive.bind(this)}> click </button>*/}
<ViewRow
id = {this.props.person.id}
fname = {this.props.person["First Name"]}
lname = {this.props.person["Last Name"]}
birthdate = {this.props.person.birthdate}
email = {this.props.person.email}
gender = {this.props.person.gender}
address = {this.props.person.address}
onClick = {this.toggleActive}
/>
<SubRow person = {this.props.person} active = {this.state.isActive} />
</React.Fragment>
);
}
};
тогда подстрока может просто сделать это
class SubRow extends Component {
render() {
return (
<tr className = {this.props.active ? undefined : "hidden">
<td colSpan = "7">
<div>
<SubRowContent
isActive = {this.props.isActive}
company = {this.props.person.company}
emplid = {this.props.person["Employee ID"]}
/>
</div>
</td>
</tr>
);
}
};
Не стесняйтесь изменять, как вам нужно, но суть есть. Когда вы устанавливаете состояние для родительского компонента, передайте этот флаг скрытому дочернему компоненту, чтобы вы могли удалить класс hidden.
передайте переменную активного состояния вашему компоненту
SubRow. Используйте эту переменную, чтобы определить классhidden