反应打字稿 - 渲染时触发按钮onclick

发布于 2025-01-21 05:43:33 字数 10317 浏览 2 评论 0原文

我在呈现一个单击功能的按钮时遇到问题,因为每当我尝试渲染它时,按钮上的onclick始终触发。

这是呈现组件的代码块:

                  <Table.Body>
                    {productNames.map((value, index) => {
                      return (
                        <Table.Row key={index}>
                          <Table.Cell>
                            <label>
                              {index}
                            </label>
                          </Table.Cell>
                          <Table.Cell>
                            <label>
                              {value}
                            </label>
                          </Table.Cell>
                          <Table.Cell>
                            <Button color="red" onClick={() => removeProduct(index) as any}>
                              Remove Product
                            </Button>
                          </Table.Cell>  
                        </Table.Row>
                        
                      )
                    })}
                  </Table.Body>

这是我的删除产品功能:

  function removeProduct(index: number) {
    const productArray: string[] = productNames;
    productArray.splice(index, 1);
    setProductNames(productArray as any);
    console.log("deleted")}

这是我的完整代码:

import React, { useState, useEffect } from "react";
import { css } from "@emotion/css";
import { Input, Button, Form, Segment, Dropdown, Grid, Icon, Table, Label } from "semantic-ui-react";
import Layout from "../common/Layout";

const inputStyle = css`
  width: 200px;
`;

const sectionStyle = css`
  margin: 1em 1em 0 1em;
`;

const optionStyle = css`
  padding: 15px;
  border-bottom: 0.5px solid #d3d3d3;
  display: flex;
  justify-content: space-between;
`;

const columnStyle = css`
  max-width: 1600px;
`;

const columnItemStyle = css`
  display: flex;
  flex-direction: row;
  gap: 5px;
`;

const buttonStyle = css`
  display: flex;
  align-items: flex-end;
  gap: 15px;
`;

const CreateDomainPage = (): JSX.Element => {
  const [domainName, setDomainName] = useState("");
  const [productNamesFieldValue, setProductNamesFieldValue] = useState("");
  const [productNames, setProductNames] = useState([]);
  const [quantitiveAttributeNames, setQuantitiveAttributeNames] = useState([]);
  const [qualitativeAttributeNames, setQualitativeAttributeNames] = useState([]);
  const [dateAttributeNames, setDateAttributeNames] = useState([]);
  const [qualitativeValueNames, setQualitativeValueNames] = useState([]);
  const [saveNewDomain, setSaveNewDomain] = useState(false);

  const handleResetButton = () => {
    setDomainName("");
    setProductNames([]);
    setQuantitiveAttributeNames([]);
    setQualitativeAttributeNames([]);
    setDateAttributeNames([]);
    setQualitativeValueNames([]);
  }

  const productOptions = [
    {key: 'a', text: 'Test a', value:'a'},
    {key: 'b', text: 'Test b', value:'b'},
    {key: 'c', text: 'Test c', value:'c'},
    {key: 'd', text: 'Test d', value:'d'},
    {key: 'e', text: 'Test e', value:'e'},
    {key: 'f', text: 'Test f', value:'f'}
  ]

  const options = [
    {key: 'b', text: 'Test a', value:'b'},
    {key: 'a', text: 'Test b', value:'a'},
    {key: 'c', text: 'Test c', value:'c'},
    {key: 'd', text: 'Test d', value:'d'},
    {key: 'e', text: 'Test e', value:'e'},
    {key: 'f', text: 'Test f', value:'f'}
  ]

  function addProduct(productName: string) {
    const productArray: string[] = productNames;
    productArray.push(productName);
    setProductNames(productArray as any);
    setProductNamesFieldValue("");
  }

  function removeProduct(index: number) {
    const productArray: string[] = productNames;
    productArray.splice(index, 1);
    setProductNames(productArray as any);
    console.log("deleted")
  }

  return (
    <Layout>
      <div className={sectionStyle}>
        <h1>Create a New Domain</h1>
        <Grid centered>
          <Grid.Column className={columnStyle}>
            <Segment>
              <Form>
                <Form.Field>
                  <label>Domain Name :</label>
                  <Input
                    className={inputStyle}
                    placeholder="Domain Name"
                    onChange={(e, {value}) => setDomainName(value)}
                    value={domainName}
                  />
                </Form.Field>
                <Form.Field>
                  <label>Product Names :</label>
                  <Input 
                    className={inputStyle}
                    placeholder="Product Names"
                    onChange={(e, {value}) => setProductNamesFieldValue(value)}
                    value={productNamesFieldValue}
                    onKeyDown={(e: KeyboardEvent) => e.key==="Enter"? addProduct(productNamesFieldValue) : null}
                  />
                  <Segment>
                    <Table celled>
                      <Table.Header>
                        <Table.Row>
                          <Table.HeaderCell>No. </Table.HeaderCell>
                          <Table.HeaderCell>Product Name</Table.HeaderCell>
                          <Table.HeaderCell>Action</Table.HeaderCell>
                        </Table.Row>
                      </Table.Header>

                      <Table.Body>
                        {productNames.map((value, index) => {
                          return (
                            <Table.Row key={index}>
                              <Table.Cell>
                                <label>
                                  {index}
                                </label>
                              </Table.Cell>
                              <Table.Cell>
                                <label>
                                  {value}
                                </label>
                              </Table.Cell>
                              <Table.Cell>
                                <Button color="red" onClick={() => removeProduct(index) as any}>
                                  Remove Product
                                </Button>
                              </Table.Cell>  
                            </Table.Row>
                            
                          )
                        })}
                      </Table.Body>
                    </Table>

                    
                  </Segment>
                </Form.Field>
                <Form.Field>
                  <label>Quantitive Attribute Names :</label>
                  <Dropdown 
                    placeholder="Quantitive Attribute Names" 
                    fluid multiple search selection
                    allowAdditions
                    // onAddItem={(event, data) => options.push({key: data.value as any, text: data.value as any, value: data.value as any})}
                    options={options}
                    onChange={(e, {value}) => setQuantitiveAttributeNames(value as any)} 
                    value={quantitiveAttributeNames}
                  />
                </Form.Field>
                <Form.Field>
                  <label>Qualitative Attribute Names :</label>
                  <Dropdown 
                    placeholder="Qualitative Attribute Names" 
                    fluid multiple search selection
                    allowAdditions
                    // onAddItem={(event, data) => options.push({key: data.value as any, text: data.value as any, value: data.value as any})}
                    options={options}
                    onChange={(e, {value}) => setQualitativeAttributeNames(value as any)} 
                    value={qualitativeAttributeNames}
                  />
                </Form.Field>
                <Form.Field>
                  <label>Date Attribute Names :</label>
                  <Dropdown 
                    placeholder="Date Attribute Names" 
                    fluid multiple search selection
                    allowAdditions
                    // onAddItem={(event, data) => options.push({key: data.value as any, text: data.value as any, value: data.value as any})}
                    options={options}
                    onChange={(e, {value}) => setDateAttributeNames(value as any)} 
                    value={dateAttributeNames}
                  />
                </Form.Field>
                <Form.Field>
                  <label>Qualitative Value Names :</label>
                  <Dropdown 
                    placeholder="Qualitative Value Names" 
                    fluid multiple search selection 
                    allowAdditions
                    // onAddItem={(event, data) => options.push({key: data.value as any, text: data.value as any, value: data.value as any})}
                    options={options}
                    onChange={(e, {value}) => setQualitativeValueNames(value as any)} 
                    value={qualitativeValueNames}
                  />
                </Form.Field>

                <Button color="teal" onClick={() => setSaveNewDomain(true)}>
                  Save Domain
                </Button>
                <Button color="red" onClick={() => handleResetButton()}>
                  Reset
                </Button>
              </Form>
            </Segment>
          </Grid.Column>
        </Grid>
      </div>
    </Layout>
  );
};

export default CreateDomainPage;

渲染时,如何避免使用此单击触发器?我试图将其绑定,但是根本无法触发onclick。我不能使用在调用OnClick内部的功能时,我不知道为什么。

编辑

我在这里发现了一些奇怪的东西,我发现问题实际上在组件中。我尝试使用onClick()函数也使用纯标签更改它,并且可以很好地奏效。

编辑

通过将type =“按钮”添加到按钮来解决的问题。

I have problems with rendering a button with onClick function, as whenever I try to render it, the onClick on the button always triggered.

This is the block of code that render the components:

                  <Table.Body>
                    {productNames.map((value, index) => {
                      return (
                        <Table.Row key={index}>
                          <Table.Cell>
                            <label>
                              {index}
                            </label>
                          </Table.Cell>
                          <Table.Cell>
                            <label>
                              {value}
                            </label>
                          </Table.Cell>
                          <Table.Cell>
                            <Button color="red" onClick={() => removeProduct(index) as any}>
                              Remove Product
                            </Button>
                          </Table.Cell>  
                        </Table.Row>
                        
                      )
                    })}
                  </Table.Body>

This is my remove product function:

  function removeProduct(index: number) {
    const productArray: string[] = productNames;
    productArray.splice(index, 1);
    setProductNames(productArray as any);
    console.log("deleted")}

This is my full code:

import React, { useState, useEffect } from "react";
import { css } from "@emotion/css";
import { Input, Button, Form, Segment, Dropdown, Grid, Icon, Table, Label } from "semantic-ui-react";
import Layout from "../common/Layout";

const inputStyle = css`
  width: 200px;
`;

const sectionStyle = css`
  margin: 1em 1em 0 1em;
`;

const optionStyle = css`
  padding: 15px;
  border-bottom: 0.5px solid #d3d3d3;
  display: flex;
  justify-content: space-between;
`;

const columnStyle = css`
  max-width: 1600px;
`;

const columnItemStyle = css`
  display: flex;
  flex-direction: row;
  gap: 5px;
`;

const buttonStyle = css`
  display: flex;
  align-items: flex-end;
  gap: 15px;
`;

const CreateDomainPage = (): JSX.Element => {
  const [domainName, setDomainName] = useState("");
  const [productNamesFieldValue, setProductNamesFieldValue] = useState("");
  const [productNames, setProductNames] = useState([]);
  const [quantitiveAttributeNames, setQuantitiveAttributeNames] = useState([]);
  const [qualitativeAttributeNames, setQualitativeAttributeNames] = useState([]);
  const [dateAttributeNames, setDateAttributeNames] = useState([]);
  const [qualitativeValueNames, setQualitativeValueNames] = useState([]);
  const [saveNewDomain, setSaveNewDomain] = useState(false);

  const handleResetButton = () => {
    setDomainName("");
    setProductNames([]);
    setQuantitiveAttributeNames([]);
    setQualitativeAttributeNames([]);
    setDateAttributeNames([]);
    setQualitativeValueNames([]);
  }

  const productOptions = [
    {key: 'a', text: 'Test a', value:'a'},
    {key: 'b', text: 'Test b', value:'b'},
    {key: 'c', text: 'Test c', value:'c'},
    {key: 'd', text: 'Test d', value:'d'},
    {key: 'e', text: 'Test e', value:'e'},
    {key: 'f', text: 'Test f', value:'f'}
  ]

  const options = [
    {key: 'b', text: 'Test a', value:'b'},
    {key: 'a', text: 'Test b', value:'a'},
    {key: 'c', text: 'Test c', value:'c'},
    {key: 'd', text: 'Test d', value:'d'},
    {key: 'e', text: 'Test e', value:'e'},
    {key: 'f', text: 'Test f', value:'f'}
  ]

  function addProduct(productName: string) {
    const productArray: string[] = productNames;
    productArray.push(productName);
    setProductNames(productArray as any);
    setProductNamesFieldValue("");
  }

  function removeProduct(index: number) {
    const productArray: string[] = productNames;
    productArray.splice(index, 1);
    setProductNames(productArray as any);
    console.log("deleted")
  }

  return (
    <Layout>
      <div className={sectionStyle}>
        <h1>Create a New Domain</h1>
        <Grid centered>
          <Grid.Column className={columnStyle}>
            <Segment>
              <Form>
                <Form.Field>
                  <label>Domain Name :</label>
                  <Input
                    className={inputStyle}
                    placeholder="Domain Name"
                    onChange={(e, {value}) => setDomainName(value)}
                    value={domainName}
                  />
                </Form.Field>
                <Form.Field>
                  <label>Product Names :</label>
                  <Input 
                    className={inputStyle}
                    placeholder="Product Names"
                    onChange={(e, {value}) => setProductNamesFieldValue(value)}
                    value={productNamesFieldValue}
                    onKeyDown={(e: KeyboardEvent) => e.key==="Enter"? addProduct(productNamesFieldValue) : null}
                  />
                  <Segment>
                    <Table celled>
                      <Table.Header>
                        <Table.Row>
                          <Table.HeaderCell>No. </Table.HeaderCell>
                          <Table.HeaderCell>Product Name</Table.HeaderCell>
                          <Table.HeaderCell>Action</Table.HeaderCell>
                        </Table.Row>
                      </Table.Header>

                      <Table.Body>
                        {productNames.map((value, index) => {
                          return (
                            <Table.Row key={index}>
                              <Table.Cell>
                                <label>
                                  {index}
                                </label>
                              </Table.Cell>
                              <Table.Cell>
                                <label>
                                  {value}
                                </label>
                              </Table.Cell>
                              <Table.Cell>
                                <Button color="red" onClick={() => removeProduct(index) as any}>
                                  Remove Product
                                </Button>
                              </Table.Cell>  
                            </Table.Row>
                            
                          )
                        })}
                      </Table.Body>
                    </Table>

                    
                  </Segment>
                </Form.Field>
                <Form.Field>
                  <label>Quantitive Attribute Names :</label>
                  <Dropdown 
                    placeholder="Quantitive Attribute Names" 
                    fluid multiple search selection
                    allowAdditions
                    // onAddItem={(event, data) => options.push({key: data.value as any, text: data.value as any, value: data.value as any})}
                    options={options}
                    onChange={(e, {value}) => setQuantitiveAttributeNames(value as any)} 
                    value={quantitiveAttributeNames}
                  />
                </Form.Field>
                <Form.Field>
                  <label>Qualitative Attribute Names :</label>
                  <Dropdown 
                    placeholder="Qualitative Attribute Names" 
                    fluid multiple search selection
                    allowAdditions
                    // onAddItem={(event, data) => options.push({key: data.value as any, text: data.value as any, value: data.value as any})}
                    options={options}
                    onChange={(e, {value}) => setQualitativeAttributeNames(value as any)} 
                    value={qualitativeAttributeNames}
                  />
                </Form.Field>
                <Form.Field>
                  <label>Date Attribute Names :</label>
                  <Dropdown 
                    placeholder="Date Attribute Names" 
                    fluid multiple search selection
                    allowAdditions
                    // onAddItem={(event, data) => options.push({key: data.value as any, text: data.value as any, value: data.value as any})}
                    options={options}
                    onChange={(e, {value}) => setDateAttributeNames(value as any)} 
                    value={dateAttributeNames}
                  />
                </Form.Field>
                <Form.Field>
                  <label>Qualitative Value Names :</label>
                  <Dropdown 
                    placeholder="Qualitative Value Names" 
                    fluid multiple search selection 
                    allowAdditions
                    // onAddItem={(event, data) => options.push({key: data.value as any, text: data.value as any, value: data.value as any})}
                    options={options}
                    onChange={(e, {value}) => setQualitativeValueNames(value as any)} 
                    value={qualitativeValueNames}
                  />
                </Form.Field>

                <Button color="teal" onClick={() => setSaveNewDomain(true)}>
                  Save Domain
                </Button>
                <Button color="red" onClick={() => handleResetButton()}>
                  Reset
                </Button>
              </Form>
            </Segment>
          </Grid.Column>
        </Grid>
      </div>
    </Layout>
  );
};

export default CreateDomainPage;

How can I avoid this onClick trigger when rendering? I've tried to bind it, but the onClick ended up cannot be triggered at all. I can't use this when calling the function inside onClick, I don't know why.

EDIT

I found out something weird here, I found out that the problems is actually in the components. I've tried to change it with pure label also with onClick() function, and it works out perfectly.

EDIT

Problem solved by adding type="button" to the button.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

扬花落满肩 2025-01-28 05:43:33

您的删除按钮没有问题,我尝试运行它并且未触发onclick按钮,我只编辑您的addproductremove> removeproduct

function addProduct() {
    setProductNames([...productNames, productNamesFieldValue]);
    setProductNamesFieldValue("");
}

function removeProduct(index: number) {
    setProductNames(productNames.filter((_: string, i: number) => i !== index));
    console.log("deleted", index);
}

保存域< /code> button

<Button color="teal" onClick={addProduct}>
    Save Domain
</Button>

here is the sandbox

There is no something wrong with your delete button, I try to run it and the onClick button not triggered, I just edit your addProduct, removeProduct

function addProduct() {
    setProductNames([...productNames, productNamesFieldValue]);
    setProductNamesFieldValue("");
}

function removeProduct(index: number) {
    setProductNames(productNames.filter((_: string, i: number) => i !== index));
    console.log("deleted", index);
}

and Save Domain button

<Button color="teal" onClick={addProduct}>
    Save Domain
</Button>

here is the sandbox click me

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文