You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Reactjs TypeError:无法获取未定义/空引用的'string'属性求助

Fixing React "Cannot read property 'string' of undefined" in PropTypes Validation

Hey there! That error you're seeing—Cannot read property 'string' of undefined—usually pops up when React can't access the PropTypes object properly. Let's break down the most common fixes for your Field component issue:

1. Make sure you've installed and imported PropTypes correctly

Starting from React 15.5.0, PropTypes aren't included in the core React package anymore—they're a separate library. If you haven't set this up yet:

  • First, install the package via npm or yarn:
    npm install prop-types
    # or
    yarn add prop-types
    
  • Then, add the import statement at the top of your Field component file:
    import PropTypes from 'prop-types';
    
    Without this import, PropTypes will be undefined, which directly causes the "cannot read 'string' property" error.

2. Check for typos or variable conflicts

Double-check that you're spelling PropTypes correctly (note the plural "s" at the end!). It's easy to accidentally write PropType (singular) which would also result in an undefined reference. Also, make sure there's no other variable in your file named PropTypes that's overriding the imported one.

3. Verify you're passing the required props to the Field component

Once you fix the PropTypes setup, you'll want to ensure any parent component using <Field> is passing the required label (a string) and onChange (a function) props. For example:

// Parent component example
import Field from './Field';

const Form = () => {
  const handleChange = (e) => {
    console.log(e.target.value);
  };

  return (
    <div>
      <Field label="Email Address" onChange={handleChange} />
    </div>
  );
};

Here's a complete, corrected version of your Field component with proper PropTypes setup:

import React from 'react';
import PropTypes from 'prop-types';

const Field = ({ label, onChange }) => {
  return (
    <div className="field">
      <label>{label}</label>
      <input type="text" onChange={onChange} />
    </div>
  );
};

Field.propTypes = {
  label: PropTypes.string.isRequired,
  onChange: PropTypes.func.isRequired,
};

export default Field;

内容的提问来源于stack exchange,提问作者Minnie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:15:04