在按钮单击上设置TextField的值

时间:2020-08-09 04:48:40

标签: reactjs material-ui

我试图在用户单击按钮时设置TextField的值。

我得到的错误是:

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

我认为这与Button有关,因为每个按钮都有onclick函数。也许有更好的解决方案?

const [txtValue, setTxtValue] = useState({})


 function campaignAmount(value){
       // alert(value)
       
            setTxtValue(value);
    }




    return (
<Grid container>
                            <Grid item lg={6}>
                        <ButtonGroup color="primary" aria-label="outlined primary button group">
                            <Button onclick={campaignAmount(300)}>$300</Button>
                            <Button onclick={campaignAmount(500)}>$500</Button>
                            <Button onclick={campaignAmount(1000)}>$1000</Button>
                        </ButtonGroup>
                        </Grid>
                        <Grid item lg={3}>
                        <TextField
                            id="campaignAmount"
                            name="campaignAmount"
                            margin="none"
                            fullWidth
                            value={`${txtValue[0]}`=== "undefined" ? '0' : `${txtValue[0]}`}
                            variant="outlined"
                            required={true}
                            />
                        </Grid>
                        </Grid>
);

更新: 我做了一些更改,现在我得到了

  Line 164:9:  'setTextValue' is not defined  no-undef

Search for the keywords to learn more about each error.

新代码

 const [txtValue, setTxtValue] = useState("0")
  function schemaTypeSelectionHandle(event) {

        // console.log('key: ', $(event.target).data('key'));
        setTextValue(event.target.attributes.getNamedItem('data-key').value);
        console.log('key: ', event.target.attributes.getNamedItem('data-key').value);
      }




    return (
     <Grid container>
                        <Grid item lg={6}>
                    <ButtonGroup color="primary"  onClick={this.schemaTypeSelectionHandle.bind(this)} aria-label="outlined primary button group">
                        <Button data-key='1'>$300</Button>
                        <Button data-key='1'>$500</Button>
                        <Button data-key='1'>>$1000</Button>
                    </ButtonGroup>
                    </Grid>
                    <Grid item lg={3}>
                    <TextField
                        id="campaignAmount"
                        name="campaignAmount"
                        margin="none"
                        fullWidth
                        value={`${txtValue[0]}`=== "undefined" ? '0' : `${txtValue[0]}`}
                        variant="outlined"
                        required={true}
                        />
                    </Grid>
                    </Grid>
);

1 个答案:

答案 0 :(得分:1)

编辑后的代码似乎运行正常。但是唯一的问题是您的打字错误。是“ setTxtValue”而不是“ setTextValue”。

您定义的钩子=> const [txtValue, setTxtValue] = useState("0")