Javascript 选中复选框时如何动态调用函数?
我正在用React构建一个简单的字符串格式应用程序,并在此过程中学习挂钩。我现在正处于我想要的阶段,当选中复选框时,调用相应的文本格式函数 例如,如果选中了小写复选框,则对输入值运行formatTextLowerCase函数。如果选中大写复选框,则对输入值运行formatTextUpperCase,依此类推。我该怎么做 请记住,我已经在使用onChange限制一次可以选中的复选框数量,目前限制为1。因此,我不确定如何设置此附加功能。我试图避免使用一堆if语句/switch语句来检查元素id之类的内容。如果您有任何帮助,我们将不胜感激 谢谢 StringFormatter.js Checkbox.js const{useState}=React; 常量复选框==>{ const[value,setValue]=useStatefalse 常量handleChange=e=>{ setValuee.target.checked } 回来 {value?'TEXT'.toLowerCase:'TEXT'} ; }; ReactDOM.render , 文件正文 ;Javascript 选中复选框时如何动态调用函数?,javascript,reactjs,Javascript,Reactjs,我正在用React构建一个简单的字符串格式应用程序,并在此过程中学习挂钩。我现在正处于我想要的阶段,当选中复选框时,调用相应的文本格式函数 例如,如果选中了小写复选框,则对输入值运行formatTextLowerCase函数。如果选中大写复选框,则对输入值运行formatTextUpperCase,依此类推。我该怎么做 请记住,我已经在使用onChange限制一次可以选中的复选框数量,目前限制为1。因此,我不确定如何设置此附加功能。我试图避免使用一堆if语句/switch语句来检查元素id之类的
嗨,Sergey,不,这不是因为我马上注意到这会导致我失去限制一次可以选中的复选框数量的功能。谢谢你的回复
import React, { useState, useRef } from 'react';
import Checkbox from './Checkbox';
const StringFormatter = () => {
const [output, setOutput] = useState('');
const [checkedBox, setCheckedBox] = useState([]);
const [errorMessage, setErrorMessage] = useState('');
const inputRef = useRef(null);
const outputRef = useRef(null);
// get value from input text area
const getInputValue = (e) => {
e.preventDefault();
return inputRef.current.value.trim();
};
// convert text to lowercase
const formatTextLowerCase = (text) => text.toLowerCase();
// convert text to lowercase
const formatTextUpperCase = (text) => text.toUpperCase();
// convert text to "web-ready"
const formatTextWebReady = (text) => {
return text
.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>{}[\]\\/]/g, '')
.replace(/\s+/g, '-')
.toLowerCase();
};
// convert text to "PeOPleFucKInGDyINg"
const formatTextPeopleFuckingDying = (text) => {
return text
.split('')
.map((v) => (Math.round(Math.random()) ? v.toUpperCase() : v.toLowerCase()))
.join('');
};
// limit number of checkboxes checked
const selectCheck = (e) => {
const selectedCheckbox = e.target;
const selectedCheckboxIsChecked = selectedCheckbox.checked;
const limit = 1;
if (selectedCheckboxIsChecked) {
if (checkedBox.length < limit) {
setCheckedBox((currentState) => [...currentState, selectedCheckbox]);
} else {
e.preventDefault();
e.target.checked = false;
}
} else {
// reset to initial state
setCheckedBox(() => []);
}
};
const displayErrorMessage = (message, duration) => {
setErrorMessage(message);
setTimeout(() => setErrorMessage(''), duration);
};
// mirror text from input field to output field
const mirrorText = (e) => {
e.preventDefault();
// get input value
// check if input value exists
// if not, display error message
const inputValue = getInputValue(e);
if (!inputValue || checkedBox.length === 0) {
displayErrorMessage('Please enter a value and/or select a box', 2250);
} else {
// if both valid, get function from formattingFn prop
// use that function to format input value
// set output value to that formatted value
console.log(checkedBox);
console.log(checkedBox.formattingFn);
console.dir(checkedBox);
}
};
return (
<form className='formatter'>
<div className='formatter__row'>
<div className='formatter__box'>
<label className='formatter__label' htmlFor='input'>
Input
</label>
<textarea
className='formatter__textarea'
name='input'
id='input'
ref={inputRef}
></textarea>
<input className='formatter__button' type='submit' value='Format' onClick={mirrorText} />
</div>
<div className='formatter__box'>
<span className='formatter__label'>Options (Pick 1)</span>
<Checkbox
onChangeFn={selectCheck}
identifier='format-lowercase'
labelText='all lowercase'
formattingFn={formatTextLowerCase}
/>
<Checkbox
onChangeFn={selectCheck}
identifier='format-uppercase'
labelText='ALL UPPERCASE'
formattingFn={formatTextUpperCase}
/>
<Checkbox
onChangeFn={selectCheck}
identifier='format-web-ready'
labelText='web-ready'
formattingFn={formatTextWebReady}
/>
<Checkbox
onChangeFn={selectCheck}
identifier='format-people-fucking-dying'
labelText='PeOPleFucKInGDyINg'
formattingFn={formatTextPeopleFuckingDying}
/>
</div>
</div>
<div className='formatter__row'>
<div className='formatter__box'>
<label className='formatter__label' htmlFor='output'>
Output
</label>
<textarea
className='formatter__textarea'
name='output'
id='output'
ref={outputRef}
value={output}
readOnly={true}
></textarea>
<button className='formatter__button'>Copy</button>
</div>
</div>
{errorMessage && <p className='formatter__error'>{errorMessage}</p>}
</form>
);
};
export default StringFormatter;
import React from 'react';
const Checkbox = ({ onChangeFn, identifier, labelText, formattingFn }) => {
return (
<div className='formatter__group'>
<input
className='formatter__check'
type='checkbox'
name={identifier}
id={identifier}
onChange={onChangeFn}
/>
<label className='formatter__check-label' htmlFor={identifier}>
{labelText}
</label>
</div>
);
};
export default Checkbox;