最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to write a custom-attribute (directive) in React 16.9? - Stack Overflow

programmeradmin3浏览0评论

Is it possible to use React just for writing a custom-attribute for existing HTML tags?

for example, I want to add float-label to an input HTML tag like the following code:

  <input type="text" id="lname" name="lname" float-label="LastName">

and call float-labels.js behind the scene. I want to just extend the regular HTML input tag no more.

Is it possible to use React to extend current HTML tags without writing a new ponent/tag (like float-input)?

Is it possible to use React just for writing a custom-attribute for existing HTML tags?

for example, I want to add float-label to an input HTML tag like the following code:

  <input type="text" id="lname" name="lname" float-label="LastName">

and call float-labels.js behind the scene. I want to just extend the regular HTML input tag no more.

Is it possible to use React to extend current HTML tags without writing a new ponent/tag (like float-input)?

Share Improve this question asked Jun 3, 2020 at 8:19 HamedFathiHamedFathi 3,9798 gold badges39 silver badges79 bronze badges 1
  • Any tags that react doesn't recognise should be transferred to the the page DOM, what happens after that is really up to you. – apokryfos Commented Jun 3, 2020 at 8:32
Add a ment  | 

4 Answers 4

Reset to default 2

You can write aria-label which will increase your code accessibility

<input type="text" id="lname" name="lname" aria-label="LastName">

You can define HTML standard attribute if you create a new attribute it will consider as props so you can define aria-label that is a built-in attribute

<input type="text" id="lname" name="lname" aria-label="LastName">

React does not have directives, you can do the following:

const CustomInput = ({ floatLabel, ...props }) => (
  <label>
    {floatLabel}
    <input {...props} />
  </label>
);
const App = () => {
  return (
    <div>
      <CustomInput type="text" floatLabel="text input label" />
      <CustomInput
        type="checkbox"
        floatLabel="checkbox input label"
      />
    </div>
  );
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>


<div id="root"></div>

You should use a data attribute instead:

  <input type="text" id="lname" name="lname" data-float-label="LastName">

This is supported, otherwise hyphen attributes will not be rendered.

发布评论

评论列表(0)

  1. 暂无评论