问题
My aim is to write code for the functionality where when I click at a particular location within the box on the screen, a spinner should show up at the location of the click.
I have Toast component (from react strap) within a div to which I have added an onClick attribute that calls markoff function on clicking. WHat markoff does is, it increases the no. of marks and adds the position of the x and y coords of the click to the state. I finally render an array of Spinner components which have absolute position set from state which was updated from mouse click. Hence the position of my click should be the place where a new Spinner component is displayed.
class AddMarkingBox extends Component {
state = {
no: 0,
mark_x: [],
mark_y: []
};
constructor(props) {
super(props);
this.markoff = this.markoff.bind(this);
}
markoff(e) {
this.setState({ no: this.state.no + 1 });
this.setState({ mark_x: [...this.state.mark_x, e.screenX] });
this.setState({ mark_y: [...this.state.mark_y, e.screenY] });
console.log(this.state);
}
render() {
const markings = [];
for (var i = 0; i < this.state.no; i += 1) {
markings.push(
<ChildComponent
key={i}
xcord={this.state.mark_x[i]}
ycord={this.state.mark_y[i]}
/>
);
}
return (
<div>
<div className="viji" onClick={this.markoff}>
<Toast>
<ToastHeader>CLICK!</ToastHeader>
<ToastBody>Click in this to add components!</ToastBody>
</Toast>
</div>
{markings}
</div>
);
}
}
const ChildComponent = props => (
<Spinner
size="sm"
color="primary"
style={{
top: props.ycord + "px",
left: props.xcord + "px",
position: "absolute"
}}
/>
);
Here's a screenshot of the browser https://drive.google.com/file/d/13OO2WHRN4zAabcA2VNQTLafo3wzvFTvl/view?usp=sharing
Instead of displaying the spinners at the same position as mouse click, they are being displayed by some x and y offset. Am I missing some positioning concepts here? Thank you.
来源:https://stackoverflow.com/questions/55556096/how-to-position-components-to-the-location-of-a-mouse-click-in-react