react-dom@15.6.1中this.refs已弃用错误及表单数据提交问题
Hey there! Let's fix that deprecated this.refs issue you're facing in React 15.6.1 while building your form to submit the questions object. Here's what you need to know and how to adjust your code:
Using this.refs is deprecated Error in React 15.6.1 Why this.refs is deprecated
React deprecated string refs (like ref="description") because they have several drawbacks—they’re less flexible, can cause inconsistencies during component updates, and don’t align with React’s preferred patterns. Even in version 15.6.1, the team encouraged developers to move away from this approach.
Solution 1: Callback Refs (Recommended for React 15.x)
Callback refs are the supported replacement for string refs in React 15. They’re straightforward and work seamlessly with your existing setup. Here's how to implement them:
Initialize ref variables in your component constructor
constructor(props) { super(props); // Create variables to hold references to your form elements this.descriptionRef = null; this.isMeetingRef = null; this.expIdRef = null; }Attach callback refs to your form elements
Replace your oldref="description"syntax with a callback function that assigns the DOM element to your ref variable:<form onSubmit={this.handleSubmit}> {/* Description textarea */} <textarea ref={(element) => { this.descriptionRef = element; }} placeholder="Enter your question description" /> {/* Is meeting checkbox */} <input type="checkbox" ref={(element) => { this.isMeetingRef = element; }} id="ismeeting" /> <label htmlFor="ismeeting">Is this a meeting question?</label> {/* Experiment ID input */} <input type="text" ref={(element) => { this.expIdRef = element; }} placeholder="Enter experiment ID" /> <button type="submit">Submit Question</button> </form>Access values in your submit handler
Now you can grab the form values directly from your ref variables, nothis.refsrequired:handleSubmit = (e) => { e.preventDefault(); // Build your questions object const questions = { description: this.descriptionRef.value, ismeeting: this.isMeetingRef.checked, expID: this.expIdRef.value }; // Send your POST request fetch('/your-backend-endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(questions) }) .then(response => response.json()) .then(data => console.log('Submission successful:', data)) .catch(error => console.error('Submission failed:', error)); };
Bonus: Controlled Components (Even Better Practice)
If you want to follow React’s best practices more closely, consider using controlled components. This means storing form values in your component’s state and updating them on every input change. It gives you more control over validation and form behavior:
Set up initial state
constructor(props) { super(props); this.state = { description: '', ismeeting: false, expID: '' }; }Add a reusable change handler
handleInputChange = (e) => { const { name, value, type, checked } = e.target; this.setState({ [name]: type === 'checkbox' ? checked : value }); };Update your form to use controlled inputs
<form onSubmit={this.handleSubmit}> <textarea name="description" value={this.state.description} onChange={this.handleInputChange} placeholder="Enter your question description" /> <input type="checkbox" name="ismeeting" checked={this.state.ismeeting} onChange={this.handleInputChange} id="ismeeting" /> <label htmlFor="ismeeting">Is this a meeting question?</label> <input type="text" name="expID" value={this.state.expID} onChange={this.handleInputChange} placeholder="Enter experiment ID" /> <button type="submit">Submit Question</button> </form>Submit using state values
handleSubmit = (e) => { e.preventDefault(); const questions = { ...this.state }; // Send your POST request (same as before) fetch('/your-backend-endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(questions) }) .then(response => response.json()) .then(data => console.log('Submission successful:', data)) .catch(error => console.error('Submission failed:', error)); };
Controlled components align with React’s one-way data flow and make it easier to add features like real-time validation or disabling the submit button until all fields are filled.
内容的提问来源于stack exchange,提问作者M.A.G

