我有一个React PureComponent,可以进行一些提取,然后返回div元素的table(list of div's)
。每个div
内部都有一些span元素。
另外,我还有另一个React Component,必须打开一些HTML元素。
我想为来自第一个React PureComponent的每个onClick()
元素在div
事件上设置第二个React Component。因此,在理想情况下,当我单击div
元素时,它必须为我打开一些模态页面。
现在当我单击div
元素时似乎什么也没发生
第一个PureComponent
import React, { Component } from "react";
import Modal from "../components/modal/form";
let test = {};
const PATH_BASE = "my url which works fine";
console.log("1st try Actions");
const i = 10;
class Actions extends React.PureComponent {
constructor() {
super();
this.state = {
result: null,
show: false
};
this.setSearchTopStories = this.setSearchTopStories.bind(this);
this.showModal = this.showModal.bind(this);
}
showModal = e => {
this.setState({
show: !this.state.show
});
};
setSearchTopStories(result) {
this.setState({ result });
}
componentDidMount() {
fetch(`${PATH_BASE}`)
.then(response => response.json())
.then(result => this.setSearchTopStories(result))
.catch(error => error);
}
render() {
const { searchTerm, result } = this.state;
console.log("* Actions Pure*");
console.log(result);
console.log("=");
return (
<div>
{result !== null
? result.map((item, index) => (
<div
onClick={() => (
<Modal onClose={this.showModal} show={this.state.show}>
Mdl--
</Modal>
)}
>
<span>{item.name}</span>
<span>{item.amount}</span>
</div>
))
: null}
</div>
);
}
}
export default Actions;
第二部分
import React from "react";
import Actions from "../../data/Actions";
export default class Modal extends React.Component {
onClose = e => {
this.props.onClose && this.props.onClose(e);
};
render() {
console.log("KLICK");
if (!this.props.show) {
return null;
}
return (
<div>
<div>{this.props.children}</div>
<div>
<button
onClick={e => {
this.onClose(e);
}}
>
Close
</button>
</div>
</div>
);
}
}
您需要将点击处理程序传递给孩子。
模态组件
export class ModalComponent extends Component {
handleChange = e => {
// do something within component first
console.log("clicked inside Modal component");
// do something from parent
this.props.handleClickFromParent(e, this.props.id);
};
render() {
return (
<div>
<button id="demo" onClick={this.handleChange}>
click me {this.props.id}
</button>
</div>
);
}
}
动作组件
export class ActionsComponent extends Component {
state = {
clicked: 0
};
handleClickFromParent = (event, id) => {
console.log(event, id);
const clicked = id;
this.setState({
clicked
});
};
render() {
return (
<div>
<ModalComponent
id={1}
handleClickFromParent={this.handleClickFromParent}
/>
<ModalComponent
id={2}
handleClickFromParent={this.handleClickFromParent}
/>
{this.state.clicked}
</div>
);
}
}