[英]how to make button click then image is opened using reactjs
我正在尝试做的是在下面的代码中,当我单击表中第一行中选中的复选框,然后单击提交按钮,然后 url 图像打开。
但是现在在我的代码中,当我单击复选框第 1 行然后自动打开图像 url 而不单击提交按钮。但是我想在单击第一行复选框时进行检查,然后单击提交按钮,然后图像在所有行中都像这样打开.
我们怎么能做到这一点。 我是这部分的新手。
任何人都帮帮我。 非常感谢
我的代码 https://codepen.io/svpan/pen/NWdJvmX
class TableComponent extends React.Component {
state = {};
handleRowClick = async (rowID) => {
// make an API call here, sth like
console.log(rowID)
const url1 = "https://grandiose-mulberry-garnet.glitch.me/query?id="+rowID;
const url2 = "https://grandiose-mulberry-garnet.glitch.me/params/"+rowID;
// const url = "https://mocki.io/v1/4d51be0b-4add-4108-8c30-df4d60e8df54";
// you can use any of the above API to test.
const response = await fetch(url1);
const res = await response.json();
// console.log(res)
this.setState({
...res,
});
window.open(res.url, '_blank');
};
render() {
var dataColumns = this.props.data.columns;
var dataRows = this.props.data.rows;
var tableHeaders = (
<thead>
<tr>
{" "}
{dataColumns.map(function (column) {
return <th> {column} </th>;
})}{" "}
</tr>{" "}
</thead>
);
var tableBody = dataRows.map((row) => {
return (
<tr onClick={() => this.handleRowClick(row.id)} key={row.id}>
{dataColumns.map(function (column) {
if(column == 'Select')
return (
<td>
<input type="checkbox" />
</td>
);
else
return (
<td>
<a target="_blank" rel="noopener noreferrer" href={row.url}>
{
row[column]
}
</a>
</td>
);
})}
</tr>
);
});
// Decorate with Bootstrap CSS
return (
<div>
<table className="table table-bordered table-hover" width="100%">
{tableHeaders} {tableBody}
</table>
<input type="submit" value="submit" />
</div>
);
}
}
// Example Data
var tableData = {
columns: ['Select','Service_Name', 'Cost/Unit'],
rows: [{
'Service_Name': 'airplan',
'Cost/Unit': 50,
'id': 1
}, {
'Service_Name': 'cat',
'Cost/Unit': 50,
'id': 2
},{
'Service_Name': 'fruits',
'Cost/Unit': 50,
'id': 5
}, {
'Service_Name': 'pool',
'Cost/Unit': 50,
'id': 4
}]
};
ReactDOM.render(
<TableComponent data = {tableData} />,
document.getElementById('table-component')
);
看起来您的问题不在提供的代码上。
我尝试做几乎与您相同的事情,但更改了您提供的 mocky.io 的 url1 和 url2。
代码看起来像这样
handleRowClick = async (rowID) => {
// make an API call here, sth like
console.log(rowID)
const url = "https://mocki.io/v1/4d51be0b-4add-4108-8c30-df4d60e8df54";
// you can use any of the above API to test.
const response = await fetch(url);
const res = await response.json();
console.log(res[0])
window.open(res[0].url, '_blank');
};
它的rest看起来一模一样。 所以,这行得通.. 情况似乎是您的问题与 CORS Allow headers 有关。 这意味着您需要更改服务器的响应(本网站 grandiose-mulberry-garnet.glitch.me)
我给你留下一些东西来咀嚼,也许它会有所帮助: Getting "TypeError: failed to fetch" when the request 实际上没有失败
首先,您需要创建一个 state 并创建一个在更改复选框时将存储 rowId 的方法
onSelectChange = (rowId) => {
this.setState({
selectedRow: rowId
});
};
现在在提交按钮上,您需要像这样调用handleRowClick
function
<input
type="submit"
value="submit"
onClick={() => this.handleRowClick(this.state.selectedRow)}
/>
工作演示在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.