Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0c20a08

Browse files
fix key in child elements
1 parent f9ce544 commit 0c20a08

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

‎src/index.spec.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -725,6 +725,26 @@ describe('reactElementToJSXString(ReactElement)', () => {
725725
);
726726
});
727727

728+
it('reactElementToJSXString(<div aprop="test" key="yes"><div aprop="test" key="yes" /></div>', () => {
729+
expect(
730+
reactElementToJSXString(
731+
<div aprop="test" key="yes">
732+
<div aprop="test" key="abc" />
733+
</div>
734+
)
735+
).toEqual(
736+
`<div
737+
key="yes"
738+
aprop="test"
739+
>
740+
<div
741+
key="abc"
742+
aprop="test"
743+
/>
744+
</div>`
745+
);
746+
});
747+
728748
it('reactElementToJSXString(<div>\\n {null}\\n</div>', () => {
729749
const element = <div>{null}</div>;
730750

‎src/parser/parseReactElement.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,9 +117,20 @@ const parseReactElement = (
117117
}
118118

119119
const key = element.key;
120-
if (typeof key === 'string' && key.search(/^\./)) {
120+
if (typeof key === 'string') {
121+
let updatedKey = key;
122+
// React automatically add ".$" to the original key when the element is a child which has a key prop
123+
if (key.indexOf('.$') === 0) {
124+
updatedKey = key.slice('.$'.length);
125+
}
121126
// React automatically add key=".X" when there are some children
122-
props.key = key;
127+
else if (key.indexOf('.') === 0) {
128+
updatedKey = null;
129+
}
130+
131+
if (updatedKey) {
132+
props.key = updatedKey;
133+
}
123134
}
124135

125136
const defaultProps = filterProps(element.type.defaultProps || {}, noChildren);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /