React中div#freezer的onClick不触发,传props遇未知属性警告
Let's break down your two issues one by one:
1. onClick on the freezer div not triggering
From your code snippet, it looks like you’ve defined the method as handleToggleMenuModal in your parent component, but you’re trying to call this.onToggleMenuModal in the div’s onClick handler. That’s a simple typo—you’re referencing a method that doesn’t exist!
Fix this by updating the onClick to use the correct method name:
<div id="freezer" onClick={this.handleToggleMenuModal}> {/* ... */} </div>
If that’s not the case, here are other common reasons this might happen:
- Unbound method: If
handleToggleMenuModalisn’t bound to the component instance,thisinside the method will beundefined. Fix this either by binding it in the constructor:
Or using an arrow function for the method (which auto-bindsconstructor(props) { super(props); // ... this.handleToggleMenuModal = this.handleToggleMenuModal.bind(this); }this):handleToggleMenuModal = () => { // your logic here this.setState(prevState => ({ menuModal: !prevState.menuModal })); } - Event propagation blocked: A child element inside the freezer div might be calling
event.stopPropagation(), which prevents the click event from bubbling up to the parent div. Check if any child components or elements have click handlers that stop propagation. - Unclickable element: Ensure the freezer div doesn’t have CSS properties like
pointer-events: noneapplied, which would make it ignore click events. Also verify it’s visible (notdisplay: noneoropacity: 0withoutpointer-events: auto).
2. Unknown Prop Warning when passing onToggleMenuModal to Template
React throws this warning when you pass a custom prop to a component that eventually passes it to a native DOM element (like <div>, <span>) which doesn’t recognize that prop as a valid HTML attribute.
For example, if your Template component spreads all props onto a DOM element like this:
class Template extends React.Component { render() { // Spreading all props onto the div includes onToggleMenuModal, which isn't a valid HTML attribute return <div {...this.props}>Some content</div>; } }
To fix this, extract the custom prop(s) from this.props before spreading the rest onto the DOM element:
class Template extends React.Component { static propTypes = { onToggleMenuModal: PropTypes.func, // Define other expected props here }; render() { // Extract the custom prop so it doesn't get passed to the div const { onToggleMenuModal, ...restProps } = this.props; // Use onToggleMenuModal in your Template component logic if needed // ... // Spread only the valid DOM props onto the div return <div {...restProps}>Some content</div>; } }
This way, you keep using the onToggleMenuModal prop in your Template component without passing it to a native DOM element, which eliminates the warning.
内容的提问来源于stack exchange,提问作者Darren

