gpt4 book ai didi

javascript - 试图获取列表项的 Prop 值

转载 作者:行者123 更新时间:2023-11-29 22:46:32 25 4
gpt4 key购买 nike

我试图获取 amount prop 和 years prop 的值,但是使用下面的代码得到了 undefined 。我已经包含了我想从中获取 Prop 值的列表项图像

let temp1;
if(amount !== null){
temp1 = amount.map((amount,i) => {
return(
<li onClick={getValue.bind(this)} key={i} amount={amount.amount} years={amount.years}>
Amount: {amount.amount} Years: {amount.years}
</li>
)
})
}

function getValue(e){
console.log(e.target.amount); //change needed
console.log(e.target.years); //change needed
}

最佳答案

您应该使用getAttribute 方法。

const amounts = [{ amount: 11, years: 10 }];

const App = () => {
return amounts.map(({ amount, years }, i) => {
return (
<li onClick={getValue} key={i} amount={amount} years={years}>
Amount: {amount} Years: {years}
</li>
);
});
};

function getValue(e) {
console.log(e.target.getAttribute('amount')); //change needed
console.log(e.target.getAttribute('years')); //change needed[enter image description here][1]
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

但是,这不是一个好的方法。将值绑定(bind)到点击会更好:

const amounts = [{ amount: 11, years: 10 }];

const App = () => {
return amounts.map(({ amount, years }, i) => {
return (
<li key={i} onClick={() => getValue({ amount, years })}>
Amount: {amount} Years: {years}
</li>
);
});
};

function getValue({ amount, years }) {
console.log(amount); //change needed
console.log(years); //change needed[enter image description here][1]
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

关于javascript - 试图获取列表项的 Prop 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58335042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com