问题描述
export default class InputView extends Component {
constructor(props) {
super(props);
this.state = {
nr: [2,3],};
}
handleDel = () => {
console.log('klick');
};
render() {
const elements = this.state.nr.map(inputPdf(nr));
return (
<div>
{elements}
</div>
);
}
}
const inputPdf = (nr) => {
return (
<div class="card">
<button type="button" class="close" aria-label="Close" onClick={this.props.handleDel()}> </button>
</div>
);
};
现在我想在子组件中使用handleDel()函数。
如何使它运行...?
解决方法
这就是我们可以做到的方式。
export default class InputView extends Component {
constructor(props) {
super(props);
this.state = {
nr: [2,3],};
}
handleDel = (indexToDelete) => {
console.log("klick");
};
render() {
const elements = this.state.nr.map((elem,index) => {
return <InputPdf item={elem} index={index} handleDel={handleDel} />
});
return <div>{elements}</div>;
}
}
const InputPdf = (props) => {
return (
<div class="card">
<button
type="button"
class="close"
aria-label="Close"
onClick={() => props.handleDel(props.index)}
>
Delete
</button>
</div>
);
};
让我知道是否有帮助
,代码中存在一些问题。但是,如果您想走自己的路。应该是这样的:
import React from "react";
import "./style.css";
class InputView extends React.Component {
constructor(props) {
super(props);
this.state = {
nr: [2,};
}
handleDel = () => {
console.log('klick');
};
render() {
const elements = this.state.nr.map((data) => inputPdf(data,this.handleDel));
return (
<div>
{elements}
</div>
);
}
}
const inputPdf = (nr,onClick) => {
return (
<div class="card">
<button type="button" class="close" aria-label="Close" onClick={onClick}>
{nr} </button>
</div>
);
};
export default function App() {
return (
<div>
<InputView/>
<p>Start editing to see some magic happen :)</p>
</div>
);
}
以下是演示:https://stackblitz.com/edit/react-txqp8k
代码中的问题
- 组件应使用大写字母
- 代替渲染{elements},您可以在render内部直接渲染这样的组件
更好的方式:
return this.state.nr.map(data => <InputPdf onClick={this.handleDel} nr={nr}/>)
//where
const InputPdf = ({nr,onClick}) => {
return (
<div class="card">
<button type="button" class="close" aria-label="Close" onClick={onClick}>
{nr} </button>
</div>
);
}